I have 2+ CDI beans that observes Java servlet context lifecycle.
@ApplicationScoped
public class ServletContextLifecycleListener1 {
public void contextInitialized(@Observes @Initialized(ApplicationScoped.class) ServletContext sc) {
}
public void contextDestroyed(@Observes @Destroyed(ApplicationScoped.class) ServletContext sc) {
}
}
@ApplicationScoped
public class ServletContextLifecycleListener2 {
public void contextInitialized(@Observes @Initialized(ApplicationScoped.class) ServletContext sc) {
}
public void contextDestroyed(@Observes @Destroyed(ApplicationScoped.class) ServletContext sc) {
}
}
My question is: This is not @ObservesAsync, This is @Observes.
Does the container make sure ServletContextLifecycleListener1.contextInitialized and ServletContextLifecycleListener2.contextInitialized get executed in the same thread? (main thread?)
The same question for contextDestroyed.
I googled, but I couldn't find my answer.
Any comments?
Thanks.
Yes, the execution happens in the same thread which is also why you can also order observers via @Priority
.
The moment you (or container) fire a synchronous event, CDI container immediately identifies all relevant observer methods, sorts them by @Priority
, and executes one at a time. Once done, the execution returns to the code which fired the event.
It behaves slightly differently for transactional observers and obviously completely differently for asynchronous observers which don't block code execution.
Related specification text can be found here (CDI 3.0 variant but this is the same for CDI 2 to CDI 4).