BBackend CourseLeroy Labs
0/0
Search the course

@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.

● intermediateHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

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)

  1. Fewer than core threads? Start a new thread.
  2. Otherwise, queue the task.
  3. Queue full? Grow toward max.
  4. 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

Hostel-Web-AppHostelBackendApplication (@EnableAsync) · notificationExecutor · EmailService

notificationExecutor 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.

Report-Manager-2shared/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).

SperoTek (in dev)shared/config/AsyncConfig · notification MailExecutorConfig

Each 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.

IR3D (Kontentt)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
  • Context propagation. SecurityContext, MDC correlation ids and tenant ThreadLocals don’t carry over to async threads automatically. Use a TaskDecorator to copy them. Otherwise your async logs lose the correlation id.
  • Exceptions in void @Async methods vanish unless you set an AsyncUncaughtExceptionHandler.
  • Transactions don’t cross threads (transactions lesson).
  • Graceful shutdown waits for executors (setWaitForTasksToCompleteOnShutdown).

Check yourself

1. Core=4, max=8, queue=200. When does the 5th thread start?
2. Main risk of @Async for password reset emails?
3. Separate executors per module illustrates…