Spring Asynchronous Execution using @Async

Introduction

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

@EnableAsync
@Configuration
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

Prerequisites

Eclipse 2019-12, Maven 3.6.3, Gradle 6.1.1, Spring Boot 2.2.5, Java at least 1.8

Create Project

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.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-async-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

    <build>
        <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>at least 8</source>
					<target>at least 8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

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

buildscript {
	ext {
		springBootVersion = '2.2.5.RELEASE'
	}
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

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

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
}

Spring Async Configuration

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

We 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;

@EnableAsync
@Configuration
public class SpringAsyncConfigurer implements AsyncConfigurer {

	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(10);
		executor.setMaxPoolSize(25);
		executor.setQueueCapacity(100);
		executor.initialize();
		return executor;
	}

	@Override
	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.

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

import java.lang.reflect.Method;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

	@Override
	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;

@RestController
public class GreetingRestController {

	@Autowired
	private GreetingService greetingService;

	@GetMapping("greet/{name}")
	public ResponseEntity<String> getGreetingMsg(@PathVariable String name)
			throws InterruptedException, ExecutionException {

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

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

	@PostMapping("log")
	public ResponseEntity<Void> logMsg() throws InterruptedException, ExecutionException {

		greetingService.logMsg();

		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 we 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;

@Service
public class GreetingService {

	@Async
	public Future<String> getGreetingMsg(final String name) throws InterruptedException {
		System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
		Thread.sleep(1000);
		return new AsyncResult<String>("Hello! Good Morning, " + name);
	}

	@Async
	public void logMsg() {
		System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());
		System.out.println("Today's date: " + new Date());
	}

}

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.

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

Source Code

download source code

Thanks for reading.

Leave a Comment