0 day streak
java / expert
Snippet

Parallel Event Dispatching with SimpleApplicationEventMulticaster

By default, Spring's ApplicationContext multicasts events synchronously. By overriding the 'applicationEventMulticaster' bean and injecting a TaskExecutor, you enable global asynchronous event processing. This is critical for high-throughput systems where event listeners perform non-blocking side effects without delaying the main execution thread.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
@Configuration
public class AsyncEventConfig {
@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster();
multicaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
multicaster.setErrorHandler(TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER);
return multicaster;
}
}
spring
Breakdown
1
SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster();
Instantiates the default implementation for event distribution.
2
multicaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
Assigns an executor to process each listener invocation in a separate thread.
3
multicaster.setErrorHandler(TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER);
Ensures that an exception in one listener does not prevent other listeners from executing.