JSR-236 has only been a half-hearted attempt at bringing asynchronous operations to the wider Java EE context, leaving many gaps or even specification bugs depending on how you see it. As of now the Concurrency Utilities for Java EE specification remains closed for Java EE 8.
One of the more painful omissions being the rather ambiguously defined CDI context propagation.
18.104.22.168 Tasks and Contexts and Dependency Injection (CDI)
CDI beans can be used as tasks. Such tasks could make use of injection if they are themselves components or
are created dynamically using various CDI APIs. However, application developers should be aware of the
following when using CDI beans as tasks:
- Tasks that are submitted to a managed instance of ExecutorService may still be running after the
lifecycle of the submitting component. Therefore, CDI beans with a scope of @RequestScoped,
@SessionScoped, or @ConversationScoped are not recommended to use as tasks as it cannot be guaranteed
that the tasks will complete before the CDI context is destroyed.
- CDI beans with a scope of @ApplicationScoped or @Dependent can be used as tasks. However, it is still
possible that the task could be running beyond the lifecycle of the submitting component, such as when
the component is destroyed.
- The transitive closure of CDI beans that are injected into tasks should follow the above guidelines
regarding their scopes.
This specification leaves a lot of room for interpretation. The current consensus is that the spawning thread’s request, session and conversation contexts are not propagated to the asynchronous process. Furthermore the request context is not even activated for the asynchronous operation (see discussion “inheritance of CDI scopes” for more details).
Continue reading Pushing ahead on Concurrency for Java EE 8