|
|
Spring Boot @Async
Author: Venkata Sudhakar
@Async is a Spring annotation that makes a method run in a separate thread instead of the calling thread. When you annotate a service method with @Async, Spring intercepts the call, submits the method to a thread pool, and returns immediately - the caller does not wait for the method to finish. This is useful for tasks that take time but whose result is not immediately needed: sending emails, writing audit logs, pushing notifications, or triggering downstream processing after saving a record. To use @Async you need two things: add @EnableAsync to a configuration class to activate the feature, and annotate the method you want to run asynchronously with @Async. The method must be in a separate Spring bean from the caller - calling @Async methods within the same class bypasses the proxy and runs synchronously. If you need the result later, return CompletableFuture instead of void. The below example shows an order service that saves an order and then fires off an email notification asynchronously so the API response returns instantly without waiting for the email to send.
The email service with the @Async method and the order service that calls it,
It gives the following output,
http-nio-8080-exec-1 - Order saved: ORD-1705312200000
http-nio-8080-exec-1 - Returning response
# API response returned to client here - no waiting!
task-1 - Sending email to [email protected]
Email sent for order ORD-1705312200000
# Notice: order thread (exec-1) and email thread (task-1) are different
# The API responded 2 seconds before the email finished sending
By default Spring uses a SimpleAsyncTaskExecutor which creates a new thread per call - not suitable for production. Define a ThreadPoolTaskExecutor bean and name it in @Async("myExecutor") to control pool size, queue capacity, and thread naming. A typical config uses corePoolSize=5, maxPoolSize=20, and queueCapacity=100 to handle bursts without overwhelming the system.
|
|