Video in progress
What traps can you run into when using @Async in Spring?
The most common ones: an @Async method called from inside the same class runs synchronously (the proxy is bypassed), if you don't configure an executor the default pool isn't what you expect, errors from void methods disappear, and ThreadLocal context doesn't carry over to the new thread.
📖 Answer
Self-invocation. @Async works through a proxy:
@Service
class ReportService {
public void generateAll() {
this.generate(1); // doesn't go through the proxy: synchronous!
}
@Async
public void generate(long id) { ... }
}
The fix is to move the method into another bean.
The executor. In Spring Boot 3 a default ThreadPoolTaskExecutor is configured (core 8, unbounded queue). All @Async methods share one pool: a slow report also blocks email sending. Give each kind of task its own executor:
@Async("mailExecutor")
public CompletableFuture<Void> sendWelcome(User u) { ... }
Errors. If you return a CompletableFuture, the error is inside that future. If it is void, and AsyncConfigurer.getAsyncUncaughtExceptionHandler() isn't configured, only a single line gets written to the log.
Context. SecurityContext, MDC and @Transactional don't carry over to the new thread. An async method doesn't run in the caller's transaction and may not see data that hasn't been committed yet. For MDC you need to write a TaskDecorator.
And don't forget @EnableAsync: without it the annotation does nothing.
Sign up to mark studied questions and save your progress.