9

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)?

Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
Mateu
  • 2,636
  • 6
  • 36
  • 54

3 Answers3

12

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.

jcwayne
  • 741
  • 4
  • 5
  • 1
    A solvable problem I see here is that the ThreadPoolExecutor needs to be aware of the thread locals. Kind of bad separation. Can be solved by an observable that throws an event once a thread finishes execution. A specific thread local can register(observer) do a cleanup once the afterExecute event is fired. – AlikElzin-kilaka Oct 26 '15 at 16:53
5

You can clear the thread local pool for a thread using reflection. You can do

public static void clearAllThreadLocals() {
    try {
        Field threadLocals = Thread.class.getDeclaredField("threadLocals");
        threadLocals.setAccessible(true);
        threadLocals.set(Thread.currentThread(), null);
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

If the thread is returned to the pool, the ThreadLocal variable will still be attached to it. When using ThreadLocals with pools, you have to be careful to be able to set when the thread is pulled from the pool and unset before it is returned.

Robin
  • 24,062
  • 5
  • 49
  • 58