Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InheritableThreadLocal and thread pools

I have a problem which I don't really think has a solution but I'll try here anyway. My application uses a thread pool and some of the threads in this pool have an inheritable thread local variable. I've extended the ThreadPoolExecutor class to essentially clear out the thread local variable (in the afterExecute call back method) when a thread is done executing.

I understand that when you have an InheritableThreadLocal variable, the childValue() method is called when the thread is initialized to get the ThreadLocal variable's value from the parent thread. However, in my case the next time the thread is used (after being used once), the value of the InheritableThreadLocal variable is null (because it was previously cleared out in afterExecute). Is there a way to access the parent thread's thread local variable in beforeExecute so that I can essentially simulate what the childValue method in InheritableThreadLocal does at the time of thread creation.

like image 672
neesh Avatar asked Sep 04 '11 00:09

neesh


1 Answers

It sounds like this is a poor use-case for the "inheritable" flavour of thread-locals.

My advice would be to just use a regular TheadLocal and do the initialization explicitly; e.g. passing the initial value from the parent thread to the child thread as a parameter or something.

(I was going suggest that you force initialization of the thread-local the child thread by having it fetch the value as soon as it starts. But that risks a race-condition; e.g. if the parent thread is returned to the pool before the child thread starts executing.)


I guess what I am asking is if there is a way to access the value of the parent thread's thread local variable from a child thread.

There isn't a way to do this.

And, judging from your other comments, I doubt that you mean "parent" and "child" in the normal sense ... where the parent thread creates the child thread.

But here's an idea. Instead of trying to share a variable between threads, share a fixed value (e.g. a request ID), and use that as a key for a shared Map. Use the Map entries as the shared variables.

like image 138
Stephen C Avatar answered Oct 17 '22 15:10

Stephen C