DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot - Async methods

Spring Boot - Async methods

Get some clarity on async methods with this tutorial that demonstrates how to enable them and annotate the related methods.

R Chaitanya user avatar by
R Chaitanya
·
Aug. 02, 20 · Tutorial
Like (14)
Save
Tweet
Share
26.16K Views

Join the DZone community and get the full member experience.

Join For Free

The key steps behind enabling Async methods in Spring are here:

1) Enable async processing in Spring Boot by annotation Spring Boot Application class with @EnableAsync

2) Create a ThreadPoolExecutor to run async methods in separate threads

3) Annotate the methods that need to be run in separate threads with @Async annotation 

This is explained in the blog post at the Spring site.

 I had a look at it and then started applying the changes in the project accordingly. It worked fine and solved the issues that we faced with performance.

In that blog post, usage of Async method was explained by creating a service method, annotated with @Asyncannotation, that makes a call to GitHub API.  

While reading the post, couple of things that struck me in that blog post:

1) When using Async methods, the return type of method must be CompletableFuture

2)  Following are the lines of code that make a call to Async service method

Code to make a call to Async service method


During debug in Eclipse, I was able to go from Line 1 to Line 2 without waiting for the service method to return the results . But I was puzzled as to how the variable in page1 got populated with the return value of the service method after the control has gone beyond Line 1.

The service method is like this:

Java
 




xxxxxxxxxx
1
10
9


 
1
  @Async
2
  public CompletableFuture<User> findUser(String user) throws InterruptedException {
3
    logger.info("Looking up " + user);
4
    String url = String.format("https://api.github.com/users/%s", user);
5
    User results = restTemplate.getForObject(url, User.class);
6
    // Artificial delay of 1s for demonstration purposes
7
    Thread.sleep(1000L);
8
    return CompletableFuture.completedFuture(results); //IT IS completedFuture
9
  }


The service method does not encapsulate the whole process in the CompletableFuture, rather all the processing is done and then at the end CompletableFuture was created to hold the results. So how is the asynchronous nature is achieved?

I started debugging. Following are my observations.

Whenever any method is annotated with @Async annotation, Spring automatically creates a proxy object for that class and injects that proxy into other classes that depend on this class. So any call to the async method goes through the proxy.

A class AsyncExecutionInterceptor intercepts the Asyncmethod calls  and  creates a CompletableFuture object and returns it.

CompletableFuture

Now the question is this. Since this interceptor class is creating CompletableFuture, why should the service method also need to do the same. Can the service method just return the object instead of wrapping it in a CompletableFuture?

The answer is "No", because the interceptor is actually called by proxy that Spring has created. To achieve async nature for methods, usage of CompletableFuture is necessary. 

But, we cannot have different return types for actual method and the method present in the proxy. Both must have same return type. That is the reason that even the service method must return value wrapped in a CompletedFuture. 

Hope this helps in understanding async methods better.

Spring Framework Spring Boot

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Implementing PEG in Java
  • Distributed Tracing: A Full Guide
  • 5 Steps for Getting Started in Deep Learning
  • What Is JavaScript Slice? Practical Examples and Guide

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: