Tech Interview RoomStudy guides

Spring

How do Spring application events and @Async work, and what are the pitfalls?

Intermediate · 2 min read · Lesson 4 of 8 in Spring

Application events

  • Publish with ApplicationEventPublisher.publishEvent(new OrderPlaced(id)); any object can be an event.
  • Listen with @EventListener methods. By default listeners run synchronously, in the publisher's thread and transaction, so an exception in a listener propagates to the publisher.
  • @TransactionalEventListener(phase = AFTER_COMMIT) runs only if, and after, the surrounding transaction commits. Good for side effects such as cache eviction or notifications.
  • Events decouple modules inside one application (a modular monolith). Spring Modulith adds an event publication registry that persists events so they survive crashes.

@Async

  • Enable with @EnableAsync; the proxy submits the method call to a TaskExecutor and returns immediately (void or CompletableFuture<T>).
  • Configure the executor explicitly (bounded queue, thread names), or in Boot 3.2+ use virtual threads.

Pitfalls

  1. Self-invocation bypasses the proxy, so the method runs synchronously.
  2. Exceptions from void async methods are lost unless an AsyncUncaughtExceptionHandler is configured.
  3. The async method runs outside the caller's transaction and without its ThreadLocal context (security context, MDC, request scope) unless a TaskDecorator propagates it.
  4. Data committed by the caller may not be visible yet if the async work starts before the commit; combine @TransactionalEventListener(AFTER_COMMIT) with @Async.
  5. In-memory async work is lost on crash or restart. Use a message broker or outbox for anything that must happen.

Example

java
@Component
class OrderNotifications {
    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void on(OrderPlaced event) {
        emailClient.sendConfirmation(event.orderId());   // runs after commit, off the request thread
    }
}

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you propagate MDC and security context to async threads?

Register a TaskDecorator on the executor that captures the context in the calling thread and restores it in the worker:

java
executor.setTaskDecorator(task -> {
    Map<String, String> mdc = MDC.getCopyOfContextMap();
    SecurityContext sec = SecurityContextHolder.getContext();
    return () -> {
        try { if (mdc != null) MDC.setContextMap(mdc); SecurityContextHolder.setContext(sec); task.run(); }
        finally { MDC.clear(); SecurityContextHolder.clearContext(); }
    };
});

With Micrometer Tracing, ContextPropagatingTaskDecorator handles trace context automatically.