Spring Asynchronous Execution using @Async


In this tutorial I will discuss about the asynchronous execution support in Spring using the @Async annotation. There are cases where Spring framework’s @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


Maven 3.6.3, Gradle 6.1.1 – 6.8.3, Spring Boot 2.2.5 – 2.4.4, Java at least 1.8

Project Setup

First step is to create a gradle or maven based project in Eclipse. The name of the project is spring-async-example.

If you are creating maven based project in Eclipse then you can use below pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


		<version>2.2.5 to 2.4.4</version>




If you are creating gradle based project in Eclipse then you can use below build.gradle script:

buildscript {
	ext {
		springBootVersion = '2.2.5.RELEASE' to 2.4.4
    repositories {
    dependencies {

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {

Spring Async Configuration

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

I have defined Thread pool executor with the custom values, such as, number of core pool, queue capacity and maximum pool size.

package com.roytuts.spring.async.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.spring.async.exception.CustomAsyncExceptionHandler;

public class SpringAsyncConfigurer implements AsyncConfigurer {

	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		return executor;

	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new CustomAsyncExceptionHandler();


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 maximum size has also been reached, then the executor will reject the task.

I 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.spring.async.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);


Spring REST controller

Create Spring REST controller class. The below REST controller has two endpoints, one is with http GET request and another is with http POST request.

package com.roytuts.spring.async.rest.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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.roytuts.spring.async.service.GreetingService;

public class GreetingRestController {

	private GreetingService greetingService;

	public ResponseEntity<String> getGreetingMsg(@PathVariable String name)
			throws InterruptedException, ExecutionException {

		String msg = greetingService.getGreetingMsg(name).get();

		return new ResponseEntity<String>(msg, HttpStatus.OK);

	public ResponseEntity<Void> logMsg() throws InterruptedException, ExecutionException {


		return new ResponseEntity<Void>(HttpStatus.OK);


Spring Service

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 you need to add extra configurations to handle exceptions.

package com.roytuts.spring.async.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 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());


If you want to get response in future then you 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.

Testing the Application

Request – GET http://localhost:8080/greet/Soumitra

Response – Hello! Good Morning, Soumitra

spring asynchronous

Request – POST http://localhost:8080/log

Response – 200 OK

Console output

Execute method asynchronously. ThreadPoolTaskExecutor-1
Execute method asynchronously. ThreadPoolTaskExecutor-2

That’s all about how to use @Async in Spring application.

Source Code


Leave a Comment