1 Reply Latest reply on Jan 14, 2015 2:18 AM by Jozef Hartinger

    CDI custom scope and threadpool

    Tony L Newbie

      Hi,

       

      I'm working on implementing some services for some given request, and I'd like to use service-specific objects in side the service code, for example a logger object that prepends service name and request id to log messages,  I built a custom service scope for that (similar to RequestScope in JavaEE while I'm using JavaSE) , the service scope stores context (service name and request id) inside some thread local variable, it works fine, however the service code may use thread pool or Collection.parallelStream() to run part of of its code in different thread, since the context stored in thread local is not available in the new thread,  and I couldn't find any easy way to propagate thread local to threads that I don't have control of, using thread local to store context does not work.

       

      I'd appreciate any suggestion on how to solve this, and I'm also wondering how does CDI scope work in general when the scope is used in different thread, as I understand most (all?) scopes use thread local to store scope context.

       

       

        • 1. Re: CDI custom scope and threadpool
          Jozef Hartinger Master

          Hi Tony,

           

          if you want the state of your context to be propagated across different threads you need to use a different storage than a ThreadLocal. For example ConcurrentHashMap. Before any piece of code is run on a given thread your code should make sure to associate the thread with the given context (e.g. use a ThreadLocal to make a note that the thread is now using the given map as its backing storage and that instances with a given service key should be used). and dissociate it at the end.