0 day streak
java / beginner
Snippet

Running Background Operations using Async and CompletableFuture

The @Async annotation marks a method to be executed on a separate thread pool managed by Spring. Wrapping the return value in a CompletableFuture allows callers to track and retrieve asynchronous computation results non-blockingly.

snippet.java
java
1
2
3
4
5
6
7
8
9
@Service
public class NotificationService {
@Async
public CompletableFuture<String> sendEmailNotification(String recipient) {
// Simulate long-running task
return CompletableFuture.completedFuture("Email sent to " + recipient);
}
}
spring
Breakdown
1
@Service
Declares the class as a Spring business service component.
2
@Async
Instructs Spring to invoke this method asynchronously in a separate background thread.
3
public CompletableFuture<String> sendEmailNotification(String recipient)
Declares the method returning a future result object representing the pending task.
4
return CompletableFuture.completedFuture("Email sent to " + recipient);
Creates an already completed CompletableFuture containing the final message value.