I’m running a process in a separate thread with a timeout, using an ExecutorService and a Future (example code here) (the thread “spawning” takes place in a AOP Aspect).
Now, the main thread is a Resteasy request. Resteasy uses one ore more ThreadLocal variables to store some context information that I need to retrieve at some point in my Rest method call. Problem is, since the Resteasy thread is running in a new thread, the ThreadLocal variables are lost.
What would be the best way to “propagate” whatever ThreadLocal variable is used by Resteasy to the new thread? It seems that Resteasy uses more than one ThreadLocal variable to keep track of context information and I would like to “blindly” transfer all the information to the new thread.
I have looked at subclassing ThreadPoolExecutor and using the beforeExecute method to pass the current thread to the pool, but I couldn’t find a way to pass the ThreadLocal variables to the pool.
Any suggestion?
Thanks
The set of
ThreadLocalinstances associated with a thread are held in private members of eachThread. Your only chance to enumerate these is to do some reflection on theThread; this way, you can override the access restrictions on the thread’s fields.Once you can get the set of
ThreadLocal, you could copy in the background threads using thebeforeExecute()andafterExecute()hooks ofThreadPoolExecutor, or by creating aRunnablewrapper for your tasks that intercepts therun()call to set an unset the necessaryThreadLocalinstances. Actually, the latter technique might work better, since it would give you a convenient place to store theThreadLocalvalues at the time the task is queued.Update: Here’s a more concrete illustration of the second approach. Contrary to my original description, all that is stored in the wrapper is the calling thread, which is interrogated when the task is executed.