@Async and errors

The starter registers Spring Boot's applicationTaskExecutor bean (alias taskExecutor), which switches @Async on for @EventListener methods: such a listener runs later instead of inside the call that published the event. Errors of scheduled runs are logged and the task keeps its schedule, unless an ErrorHandler bean takes them.

Why

Some reactions to an event should not slow the code that published it: sending a confirmation mail after an order, writing an audit entry. And a scheduled task that fails once (a server briefly down) must not stop for good, nor fail silently.

Example

@Component()
class Mailer {
  // The order is confirmed without the publisher waiting for the mail.
  @EventListener()
  @Async() // or @Async('mailExecutor') for another TaskExecutor bean
  Future<void> onPlaced(OrderPlaced order) => sendConfirmation(order);
}

// Every failed run is reported, and the task keeps running.
@Component()
class ReportErrors implements ErrorHandler {
  @override
  void handleError(Object error, StackTrace stackTrace) =>
      crashReporter.record(error, stackTrace);
}

TaskExecutor

See @Async for the listener side.

Errors of scheduled runs

An exception of a run, thrown or from the returned Future, is logged at error level to the spring.scheduling logger with the task's name, and the task keeps its schedule. Handle errors in the method if you need retries or alerts, or declare an ErrorHandler bean, which then receives every error instead of the log.

In Spring (Java)

@EnableAsync
@Configuration
class AsyncConfig {}

@Async
@EventListener
public void onPlaced(OrderPlaced order) { ... }

No @EnableAsync: the TaskExecutor bean switches it on. @Async on other bean methods is not supported. Spring sets an ErrorHandler on its ThreadPoolTaskScheduler; here the bean is found by type.

See also