@Async & thread pools: background work inside the app
Why slow work (email, push, exports) shouldn't run on the request thread, ThreadPoolTaskExecutor sizing (core, max, queue), rejection policies, named executors and losing work on restart.
The concept
Sending an email over SMTP takes 0.5–3 seconds. If signup waits for it, the user waits too, and if SMTP is down, signup fails. So you move the email off the request thread:
@Configuration
@EnableAsync
class AsyncConfig {
@Bean("notificationExecutor")
ThreadPoolTaskExecutor notificationExecutor() {
var ex = new ThreadPoolTaskExecutor();
ex.setCorePoolSize(4); // threads kept alive
ex.setMaxPoolSize(8); // grow up to this only when the queue is FULL
ex.setQueueCapacity(200); // tasks waiting
ex.setThreadNamePrefix("notify-");
ex.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // backpressure
ex.setWaitForTasksToCompleteOnShutdown(true);
ex.setAwaitTerminationSeconds(30);
ex.initialize();
return ex;
}
}
@Service
class EmailService {
@Async("notificationExecutor")
public void sendVerification(User u) { /* JavaMailSender... */ }
}
How ThreadPoolExecutor grows (often misunderstood)
- Fewer than core threads? Start a new thread.
- Otherwise, queue the task.
- Queue full? Grow toward max.
- At max with a full queue? Apply the rejection policy:
AbortPolicy(throw),CallerRunsPolicy(the request thread runs it, which slows intake as natural backpressure), or the discard policies.
With an unbounded queue, max is never reached and memory grows without limit. Always bound the queue.
In your projects
HostelBackendApplication (@EnableAsync) · notificationExecutor · EmailServicenotificationExecutor uses core 4, max 8 and a queue of 200. EmailService uses @Async("notificationExecutor") with JavaMailSender, MimeMessageHelper(MULTIPART_MODE_MIXED_RELATED) (inline images) and Thymeleaf. Web push uses sendWebPushAsync. spring.task.execution.pool (core 2, max 10, prefix MailSender-) configures Spring’s default executor separately.
shared/config/AsyncConfig.java · ResilientPublisher (notificationThreadPool)The mail pool is 2–10 threads. notificationThreadPool is also the fallback when RabbitMQ is down (see the RabbitMQ lesson).
shared/config/AsyncConfig · notification MailExecutorConfigEach module brings its own bounded executor. MailExecutorConfig uses core 2, max 4 and a queue of 200. Isolating the pools means a flood of report exports can’t starve email delivery. This is the bulkhead pattern.
BroadcastService · SystemBackgroundTasks · ClipExternalApiConfig@Async for admin broadcasts, plus a bounded shared executor for calls to external clip APIs, which caps concurrency toward rate-limited third parties.
Alternatives
| Option | Durable? | Use |
|---|---|---|
@Async + executor (yours) |
❌ | Best-effort side effects |
CompletableFuture.supplyAsync(..., executor) |
❌ | Parallel fan-out within a request |
Virtual threads (spring.threads.virtual.enabled) |
❌ | Huge I/O concurrency, no pool tuning |
| Outbox table + poller | ✅ | Reliable side effects in one DB |
| Message broker (RabbitMQ, SQS, Kafka) | ✅ | Reliable, multi-consumer, cross-service |
| Job frameworks (JobRunr, Quartz with a JDBC store) | ✅ | Scheduled and retried jobs with a dashboard |
Related concepts you must know
- Context propagation.
SecurityContext, MDC correlation ids and tenant ThreadLocals don’t carry over to async threads automatically. Use aTaskDecoratorto copy them. Otherwise your async logs lose the correlation id. - Exceptions in void
@Asyncmethods vanish unless you set anAsyncUncaughtExceptionHandler. - Transactions don’t cross threads (transactions lesson).
- Graceful shutdown waits for executors (
setWaitForTasksToCompleteOnShutdown).