2 Replies Latest reply on Aug 10, 2011 11:26 AM by ranophoenix

    How to inject into threads created with ExecutorService?

    yangju.richard.yang.pearson.com

      We have a backend process which requires the application to spawn a bunch of threads so that they can concurrently work against a task. We use ExecutorService to create and manage threads. Is there anyway to inject cdi beans into those thread workers? Since those threads are not managed by Weld, the injects failed. We ended up passing (using a setter) a reference of the injected bean (injected somewhere else) to the threads. This works but it is not direct injection to the threads.


      What the best approach to create threads and also allow injections into those threads?

        • 1. Re: How to inject into threads created with ExecutorService?
          muallin
          Hi !

          I came up with another aproach that i got somewhere else.

          Instead of moving the bean from one class to another, i just get the BeanManager from the JNDI Context, and then, get the desired bean from its pool.

          This way, you only use the bean wherever is needed.

          To help with this, i created a singleton instance that retrieved the bean.
          Hope this helps.


               private static MyBeanInterfaz getBean() throws NamingException {
                    InitialContext jndiContext = new InitialContext();
                    BeanManager manager = (BeanManager) jndiContext.lookup("java:/comp/env/BeanManager");
                    Bean<MyBeanInterfaz> bean = (Bean<MyBeanInterfaz>) manager.getBeans(MyBeanInterfaz.class).iterator().next();
                    CreationalContext<MyBeanInterfaz> ctx = manager.createCreationalContext(bean);
               
                    MyBeanInterfaz interfaz = (MyBeanInterfaz) manager.getReference(bean,     MyBeanInterfaz.class, ctx);
                    return interfaz;
               }|
          • 2. Re: How to inject into threads created with ExecutorService?
            ranophoenix

            Hi,


            You can use generics:


                public static <T> T getBean(Class clazz) {
                    BeanManager bm = getBeanManager();
                    Bean<T> bean = (Bean<T>) bm.getBeans(clazz).iterator().next();
                    CreationalContext<T> ctx = bm.createCreationalContext(bean);
                    T cdiBean = (T) bm.getReference(bean, clazz.getClass(), ctx);
            
                    return cdiBean;
                }
            



            From: http://osgijee.googlecode.com/hg/webclient/src/main/java/ranophoenix/osgijee/webclient/impl/cdi/Util.java