Understanding Synchronous vs Asynchronous Event Execution in Spring's SimpleApplicationEventMulticaster
After upgrading a core component, a previously synchronous domain event in Spring became asynchronous, causing runtime errors; this article explains the underlying mechanism, shows the relevant source code of SimpleApplicationEventMulticaster, and clarifies how the presence or absence of a configured thread pool determines whether events are processed synchronously or asynchronously.
After upgrading a core component, a domain event that was originally executed synchronously in a Spring application started executing asynchronously, leading to business runtime errors.
The execution mode is decided by the SimpleApplicationEventMulticaster implementation. When an event is published, the multicastEvent method checks whether a task executor (thread pool) is configured; if it exists, the listener is invoked via the executor (asynchronously), otherwise it is invoked directly (synchronously).
org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)
@Override public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); Executor executor = getTaskExecutor(); for (ApplicationListener listener : getApplicationListeners(event, type)) { if (executor != null) { executor.execute(() -> invokeListener(listener, event)); } else { invokeListener(listener, event); } } }
The task executor field itself can be null:
@Nullable private Executor taskExecutor;
If the application context does not define a custom ApplicationEventMulticaster , Spring creates a default SimpleApplicationEventMulticaster without a thread pool, which means events are processed synchronously.
org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster
In summary, Spring events are synchronous by default; configuring a thread pool either on the default multicaster or on a custom implementation makes the event handling asynchronous.
Source: spring-cloud-context-3.1.1
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.