0 day streak
java / beginner
Snippet

Dispatching Non-Blocking Tasks with the Async Annotation

Spring enables asynchronous method execution via @EnableAsync and @Async. When a method annotated with @Async is invoked, Spring offloads its execution to a separate thread pool instead of blocking the calling thread. Returning a CompletableFuture lets the caller retrieve the eventual result or continue processing immediately.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
@EnableAsync
public class AppAsyncConfig {
}
@Service
public class NotificationService {
@Async
public CompletableFuture<String> sendWelcomeEmail(String recipient) {
try {
Thread.sleep(1000); // Simulate network latency
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return CompletableFuture.completedFuture("Sent email to " + recipient);
}
}
spring
Breakdown
1
@EnableAsync
Enables Spring's asynchronous method processing capability across the entire application context.
2
@Async
Instructs Spring to execute this specific method asynchronously in a separate worker thread.
3
return CompletableFuture.completedFuture("Sent email to " + recipient);
Wraps the return value inside a CompletableFuture so the caller can observe the completed background result.