java / beginner
Snippet
Returning Non-Blocking Results with Async CompletableFuture
Combining Spring's @Async annotation with Java's CompletableFuture executes methods on a separate thread pool asynchronously, preventing slow I/O operations from blocking the calling execution flow.
snippet.java
java
1
2
3
4
5
6
7
8
@Servicepublic class NotificationService {@Asyncpublic CompletableFuture<String> sendWelcomeEmail(String recipient) {return CompletableFuture.completedFuture("Email sent to " + recipient);}}
spring
Breakdown
1
@Service
Registers the NotificationService class as a Spring bean within the container.
2
@Async
Instructs Spring to invoke this method in a separate background thread from the configured task executor.
3
public CompletableFuture<String> sendWelcomeEmail(String recipient) {
Defines the asynchronous method returning a CompletableFuture wrapper around the String result.
4
return CompletableFuture.completedFuture("Email sent to " + recipient);
Wraps the completed return message inside an already-resolved CompletableFuture instance.