Video in progress

Strong Middle 🌱 Spring

What is wrong with this @Async executor configuration, and how does it behave under load?

@Bean
ThreadPoolTaskExecutor mailExecutor() {
    ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
    ex.setCorePoolSize(5);
    ex.setMaxPoolSize(50);
    // queueCapacity default: Integer.MAX_VALUE
    ex.initialize();
    return ex;
}

ThreadPoolTaskExecutor doesn't create new threads until the queue is full. Because the queue is unbounded, the pool never grows to 50 threads: it always runs 5 threads, while tasks pile up in the queue and fill memory.

📖 Answer

Most people think maxPoolSize means "when load grows, threads increase up to 50". The real order in ThreadPoolExecutor is:

  1. if there are fewer threads than corePoolSize, a new thread;
  2. otherwise, the task goes into the queue;
  3. if the queue is full, a new thread up to maxPoolSize;
  4. if that's full too, the RejectedExecutionHandler.

If the queue is Integer.MAX_VALUE, step 3 is never reached. If the mail server slows down, a million tasks sit in the queue, the heap fills up, and on restart everything is lost.

A better configuration:

@Bean
ThreadPoolTaskExecutor mailExecutor() {
    ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
    ex.setCorePoolSize(10);
    ex.setMaxPoolSize(20);
    ex.setQueueCapacity(500);
    ex.setThreadNamePrefix("mail-");
    ex.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // backpressure
    ex.setWaitForTasksToCompleteOnShutdown(true);
    ex.setAwaitTerminationSeconds(30);
    ex.initialize();
    return ex;
}

And on the method: @Async("mailExecutor").

A few more points:

  • Spring Boot creates its own applicationTaskExecutor (8 core threads, unbounded queue), configured with spring.task.execution.pool.*; in Boot 3.2+, if virtual threads are enabled, it's replaced by SimpleAsyncTaskExecutor.
  • CallerRunsPolicy: the task runs on the calling thread, so the request slows down, but nothing is lost.
  • Export the queue length as a metric; executor.queued is ready-made in Micrometer.
  • For work that must not be lost (money, notifications), you need an outbox table or a broker, not an in-memory queue.