Java Cached thread pool and thread local

Mateu picture Mateu · Sep 13, 2011 · Viewed 8.2k times · Source

I have a question about java and concurrency.

Let say I have a ThreadLocal variable called 'a'. And I use a CachedThreadPool to obtain new threads. When a thread is reused, what happens to the ThreadLocal variable 'a'? It maintains the same value (cause it is the same thread) or it starts empty (as if the thread was new)?

Answer

jcwayne picture jcwayne · Sep 13, 2011

By default ThreadLocals are reused along with the thread. If you need them to be be reinitialized you can do so by overriding the methods noted below:

from javadoc for java.util.concurrent.ThreadPoolExecutor

Hook methods This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.