Tuesday, January 12, 2021

Java InheritableThreadLocal Does not Work Well with ThreadPool

    One of the dev's brought up the topic of InhertiableThreadLocal, which is a ThreadLocal whose value is copied from the parent thread to local thread. This first appeared to be an amazing feature. However, in the fine text, it says:

“Whenever that thread creates a new thread (a child thread), the InheritableThreadLocal object is automatically updated so that the new child thread has the same value associated with it as the parent thread”

    It means the copying process only happens during the creation. The Parent Thread and Child Thread relation relies on creation. This becomes an issue when you are using a ThreadPool, where the threads are reused instead being created. Some other people also encountered this issue:

So in conclusion, InheritableThreadLocal is not a good idea. Use caution when you are working with it.

How else would I pass ThreadLocal values across thread?

    You will want to copy the values in ThreadLocal variables as a field of a Runnable in the constructor. This creates a context for your Runnable. In your Runnable.run(), apply the values in the context to the ThreadLocal variables again. The allows ThreadLocal to be copied over because the constructor runs in your caller thread, while Runnable.run() runs in the invoked thread.