java / intermediate
Snippet
Asynchronous Processing with @Async
The @Async annotation allows a method to execute in a separate thread. Returning a CompletableFuture lets the caller track the result later.
snippet.java
1
2
3
4
5
6
7
8
9
10
@Servicepublic class EmailService {@Asyncpublic CompletableFuture<Boolean> sendEmail(String recipient) {// Simulate long-running taskThread.sleep(2000);return CompletableFuture.completedFuture(true);}}
spring
Breakdown
1
@Async
Marks the method as a candidate for asynchronous execution.
2
CompletableFuture<Boolean>
A container for a value that will be available in the future.