java / beginner
Snippet
Running Non-Blocking Background Tasks Using Async
The @Async annotation delegates method execution to a background thread pool, allowing calling methods to continue running without blocking on slow tasks.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
@Servicepublic class NotificationService {@Asyncpublic CompletableFuture<String> sendEmailNotification(String recipientEmail) {// Simulating a background taskString status = "Delivered to: " + recipientEmail;return CompletableFuture.completedFuture(status);}}
spring
Breakdown
1
@Async
Instructs Spring to execute the annotated method in a separate thread from the task executor pool.
2
public CompletableFuture<String> sendEmailNotification(String recipientEmail)
Declares an asynchronous method that wraps the eventual result in a CompletableFuture container.
3
return CompletableFuture.completedFuture(status);
Returns an already completed asynchronous future holding the result string.