3 Replies Latest reply on Mar 31, 2012 12:35 PM by christopherp

    Weld CDI context propagation

    rabiter

      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:

      http://seamframework.org/Documentation/IfICreateAThreadInMyCDIBeanHowWillWeldReact

       

      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 propagation
          christopherp

          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: http://java.net/jira/browse/GLASSFISH-17152

          But note that it's not a bug, it's just undefined behavior.

           

          Hope that helps!

          • 2. Re: Weld CDI context propagation
            rabiter

            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 propagation
              christopherp

              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!