Skip to main content

Asynchronous REST service implementation in Spring boot

In this tutorial we will see how to create an asynchronous REST service endpoint using Spring boot application.
Asynchronous service works in a way that it will not block the client request and do the processing in separate thread. When work is complete the response returned to the client so our service will be able to handle more client requests at the same time, compare to synchronous processing model.
Let's understand how it is working in synchronous mode. In such server/client application at server side it has a pool of threads which are serving the request. If a request received by a thread then it will be blocked until it send the response back to client. In this case if processing doesn't take much time it will be able to process it quickly and accept other client requests but there could be one situation when all threads are busy and not able to accept the new client requests.
synchronous communication

To overcome of such problems, asynchronous processing model introduced for REST services. In this processing model, after receiving the request from client it creates a separate worker thread to process the request and request thread becomes available to accept the more requests. Worker thread send the response back to client once it completes the processing.
asynchronous communication

Here we are going to see how to implement asynchronous REST service using Spring boot application, however now JAX-RS 2 also supports asynchronous communication but Spring uses it's own API for REST implementation.

Maven dependencies



First we need to add this annotation on any configuration class or spring boot main class. Configuration classes are those who have the annotation @Configuration. We need this annotation to enable the asynchronous execution capabilities of Spring. Once async is enable Spring will look for the task executor bean and if it is not found then Spring will use SimpleAsyncTaskExecutor to execute the tasks asynchronously.
  public class SpringBootTutorialApplication
Task executor is optional but may be useful depending on our requirement as we can tune it as per need. I am putting it here for your reference but it's your choice whether you want to customize it or not. We need to use the @EnableAsync annotation and implement the interface AsyncConfigurer. Below is code for the task executor implementation.
public class SpringBootTutorialApplication implements AsyncConfigurer{
    public static void main(String[] args) {, args);

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

Async REST service

Now we need to create the REST service which execute asynchronously using the WebAsyncTask. WebAsyncTask is a Spring class which needs Callable task to get initialized and then this instance we need to return from our REST endpoint.
It comes with various constructor implementation using which we can supply timeout and custom executors also. Also it provides some callback methods which can be executed on success, error or timeout events for this task. See the below code of our REST service.
public class AsyncRestController {
    public WebAsyncTask sayHello(@RequestParam(defaultValue="Demo user") String name){
        System.out.println("service start...");
        WebAsyncTask task = new WebAsyncTask(4000, () -> {
            System.out.println("task execution start...");
            int waitSeconds = 2;
            if("timeout".equals(name)) {
                waitSeconds = 5;
            Thread.sleep(waitSeconds * 1000);
            if("error".equals(name)) {
                throw new RuntimeException("Manual exception at runtime");
            System.out.println("task execution end...");
            return "Welcome "+name+"!";
            return "Request timed out...";
            return "Some error occurred...";
        System.out.println("service end...");
        return task;
In above code we have one REST endpoint "/hello" which accepts a name returns the response after 2 seconds. We are returning an instance of WebAsyncTask which is configured to be timeout after 4 seconds. We will test here below 3 scenarios to see the different response for each of the above callback methods.

1. Success response

In this case it returns response in 2 seconds and "onCompletion" callback method is executed. Here in console output we can see that our logic is executed asynchronously and response has return once it was ready to send after 2 seconds.
URL: http://localhost:8080/hello?name=Akshay
    Welcome Akshay!
Console output:
   service start...
   service end...
   task execution start...
   task execution end...

2. Time out response

Since service is not able to send the response before configured timeout, it will time out and callback method for "onTimout" will be executed. In the console output it shows that even though timeout has occurred, it has executed the callback method for onTimout as well as onCompletion.
URL: http://localhost:8080/hello?name=timeout
    Request timed out...
Console output:
   service start...
   service end...
   task execution start...

3. Error response

In this case, we generate the manual exception which results in the execution of "onError" callback method. By seeing the console output it is clear that it throws exception and executes two callback methods "onError" and "onCompletion".
URL: http://localhost:8080/hello?name=error
    Returns Spring's error page.
Console output:
    service start...
    service end...
    task execution start...
    java.lang.RuntimeException: Manual exception at runtime


  1. I have read your excellent post. This is a great job. I have enjoyed reading your post first time. I want to say thanks for this post. Thank you…ufabet168

  2. This is a really authentic and informative blog. Share more posts like this.
    OpenStack In Cloud Computing
    Features Of OpenStack

  3. this greatful informative of us. thanks for sharing. Kinemaster Gold

  4. Thanks for this useful blog, keep sharing your thoughts...
    Unix Program
    Unix Applications

  5. Thanks for sharing such an informative Article. I really Enjoyed. It was great reading this article. Keep posting more articles on
    Big Data Solutions 
    Advanced Data Analytics Services

  6. Tamiloneindia has a strong print and online membership base. Over 36 million unique visitors visit latimes each month. The site’s attention to detail makes it an excellent choice both for those in the LA area and all around the world. You can stay on top of the latest sports news, politics, entertainment, and more with Tamil One India.

  7. Download Mod Games APK, A2Z APK, Mod APK, Mod APPS, Mod Games, Android Application, Free Android App, Android Apps, Android APK


Post a Comment

Popular Posts

Setting up kerberos in Mac OS X

Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database. Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application. Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below. brew install krb5 Once installation is complete, we need to set the below export commands in user's profile which will make the kerberos utility commands and compiler available to execute from anywhere. Open user's bash profile: vi ~/.bash_profile Add below lines: export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS=&

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check. havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false. matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment. name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"} prefix - It can be use when you want to apply some prefix to

Why HashMap key should be immutable in java

HashMap is used to store the data in key, value pair where key is unique and value can be store or retrieve using the key. Any class can be a candidate for the map key if it follows below rules. 1. Overrides hashcode() and equals() method.   Map stores the data using hashcode() and equals() method from key. To store a value against a given key, map first calls key's hashcode() and then uses it to calculate the index position in backed array by applying some hashing function. For each index position it has a bucket which is a LinkedList and changed to Node from java 8. Then it will iterate through all the element and will check the equality with key by calling it's equals() method if a match is found, it will update the value with the new value otherwise it will add the new entry with given key and value. In the same way it check for the existing key when get() is called. If it finds a match for given key in the bucket with given hashcode(), it will return the value other

jaxb2-maven-plugin to generate java code from XSD schema

In this tutorial I will show how to generate the Java source code from XSD schema. I will use jaxb2-maven-plugin to generate the code using XSD file which will be declared in pom.xml to make it part of build, so when maven build is executed it will generate the java code using XSD. Class generation can be controlled in plugin configuration. Maven changes (pom.xml) Include below plugin in your pom.xml. Here we have done some configuration under configuration section as given below. schemaDirectory : This is the directory where I keep my schema (XSD file). outputDirectory : This is the java source location where I want to generate the Java files. If it is not given then by default it will be generate inside target folder. clearOutputDir : If this property is true then it will generate the classes on each build otherwise it will generate only if output directory is empty. <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</art