Member-only story
How to Implement Asynchronous Calls in Spring Boot with @Async
This article is about how asynchronous behaviour can be achieved in spring boot.
- Synchronous Programming: In synchronous programming, tasks are performed one at a time and only when one is completed the next is unblocked.
- Asynchronous Programming: In asynchronous programming, multiple tasks can be executed simultaneously. You can move to another task before the previous one finishes.
In spring boot, we can achieve asynchronous behaviour using @Async annotation. But just @Async annotation will not work. For that, you need to understand how @Async internally works.
Spring comes with @EnableAsync
annotation and can be applied to a @Configuration class for asynchronous behavior. The @EnableAsync
annotation will look for methods marked with @Async
annotation and run them in background thread pools.
The @Async
annotated methods are executed in a separate thread and return CompletableFuture
to hold the result of an asynchronous computation.
To enable async configuration in spring, follow these steps:
- Create a thread pool to run…