0 day streak
java / intermediate
Snippet

Asynchronous Execution with @Async

The @Async annotation allows a method to run in a separate thread pool. The caller does not wait for the method to complete, making it ideal for background tasks like sending emails or notifications.

snippet.java
java
1
2
3
4
5
6
7
8
@Service
public class MailService {
@Async
public void sendWelcomeEmail(String email) {
// Simulate network latency for sending mail
smtpClient.send(email, "Welcome to our app!");
}
}
spring
Breakdown
1
@Async
Instructs Spring to wrap the method call in a proxy that executes it on a background thread.
2
public void sendWelcomeEmail(String email)
This method must return void or a Future/CompletableFuture to work correctly with async proxying.