Video in progress

Middle 🌱 Spring

How does @Async work, and which thread does it run on?

With @EnableAsync, Spring wraps the bean in a proxy. When you call an @Async method, the work is handed to an executor and the caller moves on without waiting. In Boot the default is a ThreadPoolTaskExecutor (threads named task-).

📖 Answer

@Configuration
@EnableAsync
class AsyncConfig { }

@Service
class NotificationService {
    @Async
    public void sendWelcome(long userId) { ... } // on a separate thread

    @Async
    public CompletableFuture<Report> build(long id) {
        return CompletableFuture.completedFuture(makeReport(id));
    }
}

Tuning the Boot pool:

spring:
  task:
    execution:
      pool:
        core-size: 4
        max-size: 16
        queue-capacity: 500

Where people trip up:

  • if you call it from the same class (self-invocation), @Async doesn't work;
  • the new thread doesn't see the caller's transaction — the async method may not find a record that hasn't been committed yet;
  • the SecurityContext and MDC (the trace id in logs) don't carry over to the new thread; you need a TaskDecorator for that;
  • an exception in a void method never reaches the caller;
  • an unbounded queue will eat up memory — put a limit on it.