Weld CDI context propagationIvan Ivanov Mar 20, 2012 6:07 AM
Hi, friends!
I'm using the @SessionScoped CDI bean, which works perfectly. But the fact is that during the execution I have to create a new thread (I'm using the @Asynchronous annotation for this purpose). And, of course, weld doesn't propagate the @SessionScoped bean to the newly created thread. I've found some information about this issue here:
But I wasn't able to solve my problem. Is it possible to propagate the Context to newly created thread too?
For example:
@Stateless
public class Runner {
@Inject
private MySession session; // this is the @SessionScoped bean
// this method will be called in a new thread
@Asynchronous
public void doTask() {
// do some heavy long running work
...
session.setResult(result); // oops - an error:
// WELD-001303 No active contexts for scope type javax.enterprise.context.SessionScoped
}
}
Thanks!
1. Re: Weld CDI context propagationchristopherp Mar 29, 2012 11:47 AM (in response to Ivan Ivanov)
Looks like I ran into the same problem as you Ivan. I found a way to work around the problem by using a database to store a CDI message queue for each user. The CDI messages can be left by asynchronous threads, and then picked up within the user's session context. This glassfish ticket relates to the same problem:
But note that it's not a bug, it's just undefined behavior.
Hope that helps!
2. Re: Weld CDI context propagationIvan Ivanov Mar 30, 2012 10:39 AM (in response to christopherp)
Thanks for your replay!
So if I've got it correctly, you use a database as a storage for results of asynchronously executed tasks. And then, each user's SessionScoped (or RequestScoped) bean can pick the result manually from the database. Yep... this is the first solution I've got in my mind. But instead of the database, I use ApplicationScoped bean (in my case it is quite satisfactorily).
3. Re: Weld CDI context propagationchristopherp Mar 31, 2012 12:35 PM (in response to Ivan Ivanov)
Yep, either would work fine. ApplicationScoped bean would make it simpler actually. I have to make sure all messages and data trasfer objects are serializable. You wouldn't have to worry about that with an ApplicationScoped bean.
Good luck!