0 day streak
java / beginner
Snippet

Executing Background Tasks with CompletableFuture

Spring supports asynchronous method invocation to run long-running operations in separate threads. By marking a method with @Async and returning a CompletableFuture, callers can trigger tasks without blocking the main execution thread.

snippet.java
java
1
2
3
4
5
6
7
8
9
@Service
public class NotificationService {
@Async
public CompletableFuture<String> sendEmailNotification(String recipientEmail) {
// Simulates a time-consuming email delivery process
return CompletableFuture.completedFuture("Email sent to " + recipientEmail);
}
}
spring
Breakdown
1
@Async
Indicates that the method should be executed asynchronously in a separate worker thread pool.
2
public CompletableFuture<String> sendEmailNotification(String recipientEmail)
Defines a method signature returning a generic CompletableFuture container holding the final result.
3
return CompletableFuture.completedFuture("Email sent to " + recipientEmail);
Wraps the outcome in an already completed asynchronous future.