In this tutorial we will discuss about the asynchronous execution support in Spring using the @Async annotation. There are cases in which @Async is necessary to execute piece of code asynchronous. An example would be while sending a (JMS) message from one system to another system. The advantage is that the user does not have to wait for the response while the message is being send.

@Async annotation on a method of a bean will execute in a separate thread i.e. the caller does not need to wait for the completion of the called method.

Enabling Async Support

The @EnableAsync annotation switches on Spring’s ability to run @Async methods in a background thread pool. For Enabling asynchronous processing with Java configuration got by simply adding the @EnableAsync to a configuration class

public class SpringAsyncConfigurer implements AsyncConfigurer {...}

Limitations of @Async

  • It is applicable only to the public methods
  • Calling the @Async method within the same class would not work


Eclipse Neon
Maven 3.3.9
Spring 4.3.8.RELEASE
Jackson 2.5.3
Java 1.8

Example with Source Code

Maven Configuration

Maven Dependency – pom.xml.

<project xmlns="" xmlns:xsi=""
	<name>spring-async Maven Webapp</name>
		<!-- Spring mvc -->
		<!-- jackson -->
		<!-- Servlet -->
		<!-- jstl -->

Spring MVC Configuration Class

Create below Spring configuration class that will provide facilities for component scanning, annotation based MVC etc.

package com.roytuts.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@ComponentScan(basePackages = "com.roytuts")
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

Spring MVC Initializer Class

Create below Spring initializer class that helps us to load Dispatcher Servlet and other Spring configurations.

package com.roytuts.config;
import javax.servlet.Filter;
import com.roytuts.filter.SameOriginPolicyFilter;
public class WebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { WebMvcConfigurer.class, SpringAsyncConfigurer.class };
	protected Class<?>[] getServletConfigClasses() {
		return null;
	protected String[] getServletMappings() {
		return new String[] { "/" };
	protected Filter[] getServletFilters() {
		Filter[] singleton = { new SameOriginPolicyFilter() };
		return singleton;

CORS Filter

Create below filter to handle issues related to the Same Origin Policy(SOP). SOP is an important security concept in browsers. SOP allows client-side programming languages, such as JavaScript, only access to resources in the same domain. SOP is very important for internet applications, because you want to prevent, that everybody can access to your services and content.

For more information on SOP please refer to the link and

package com.roytuts.filter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class SameOriginPolicyFilter implements Filter {
	public void init(FilterConfig filterConfig) {
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) resp;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "X-requested-with, Content-Type");
		chain.doFilter(req, resp);
	public void destroy() {

Spring Async Configuration Class

Create below configuration class for @Async support for the application.

package com.roytuts.config;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.roytuts.exception.CustomAsyncExceptionHandler;
public class SpringAsyncConfigurer implements AsyncConfigurer {
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		return executor;
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new CustomAsyncExceptionHandler();

Creating Thread Pool Executor

ThreadPoolTaskExecutor – the main idea is that when a task is submitted, the executor will first try to use a free thread if the number of active threads is currently less than the core size. If the core size has been reached, then the task will be added to the queue as long as its capacity has not yet been reached. Only then, if the queue’s capacity has been reached, will the executor create a new thread beyond the core size. If the max size has also been reached, then the executor will reject the task.

We have created a custom async exception handler by implementing AsyncUncaughtExceptionHandler interface to invoke handleUncaughtException() method when there is any uncaught asynchronous exceptions.

package com.roytuts.exception;
import java.lang.reflect.Method;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
	public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
		System.out.println("Exception message - " + throwable.getMessage());
		System.out.println("Method name - " + method.getName());
		for (Object param : obj) {
			System.out.println("Parameter value - " + param);

Creating Spring REST controller

Create Spring REST controller class.

package com.roytuts.controller;
import java.util.concurrent.ExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.roytuts.service.GreetingService;
public class GreetingRestController {
	private GreetingService greetingService;
	@RequestMapping(value = "greet/{name}", method = RequestMethod.GET)
	public ResponseEntity<String> getGreetingMsg(@PathVariable String name)
			throws InterruptedException, ExecutionException {
		String msg = greetingService.getGreetingMsg(name).get();
		return new ResponseEntity<String>(msg, HttpStatus.OK);
	@RequestMapping(value = "log", method = RequestMethod.POST)
	public ResponseEntity<Void> logMsg() throws InterruptedException, ExecutionException {
		return new ResponseEntity<Void>(HttpStatus.OK);

Create Spring Service Class

Service interface.

package com.roytuts.service;
import java.util.concurrent.Future;
public interface GreetingService {
	Future<String> getGreetingMsg(String name) throws InterruptedException;
	void logMsg();

When a method return type is a Future, exception handling is easy – Future.get() method will throw the exception. But, if the return type of a method is void, exceptions will not be propagated to the calling thread. Hence we need to add extra configurations to handle exceptions.

If we want to get response in future then we can apply @Async to a method with return type – by wrapping the actual return in a Future. Spring provides a AsyncResult class which implements Future. This can be used to track the result of asynchronous method execution.

The implementation code for the above interface:

package com.roytuts.service;
import java.util.Date;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
public class GreetingServiceImpl implements GreetingService {
	public Future<String> getGreetingMsg(final String name) throws InterruptedException {
		System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
		return new AsyncResult<String>("Hello! Good Morning, " + name);
	public void logMsg() {
		System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
		System.out.println("Today's date: " + new Date());

Testing the Application

request – GET http://localhost:8080/spring-async/greet/Soumitra

response – Hello! Good Morning, Soumitra

request – POST http://localhost:8080/spring-async/log

response – 200 OK

Console output

Execute method asynchronously. ThreadPoolTaskExecutor-1
Execute method asynchronously. ThreadPoolTaskExecutor-2
Today's date: Fri Jun 09 08:21:51 IST 2017

Source Code

Thanks for reading.


Leave a Reply

Your email address will not be published. Required fields are marked *