Will the ThreadLocal object be cleared after thread returned to Thread Pool?

Rahul Vedpathak picture Rahul Vedpathak · May 19, 2015 · Viewed 7.1k times · Source

Will the contents that are stored in the ThreadLocal storage during an execution be cleared automatically when the thread is returned to ThreadPool (as would be expected) ??

In my application I am putting some data in ThreadLocal during some execution but if next time the same Thread is being used, then I am finding the obsolete data in ThreadLocal storage.

Answer

Peter Lawrey picture Peter Lawrey · May 19, 2015

The ThreadLocal and ThreadPool don't interact with one another unless you do this.

What you can do is a a single ThreadLocal which stores all the state you want to hold and have this be reset when the task completes. You can override ThreadPoolExecutor.afterExecute (or beforeExecute) to clear your ThreadLocal(s)

From ThreadPoolExecutor

/**
 * Method invoked upon completion of execution of the given Runnable.
 * This method is invoked by the thread that executed the task. If
 * non-null, the Throwable is the uncaught {@code RuntimeException}
 * or {@code Error} that caused execution to terminate abruptly.
 *
 * <p>This implementation does nothing, but may be customized in
 * subclasses. Note: To properly nest multiple overridings, subclasses
 * should generally invoke {@code super.afterExecute} at the
 * beginning of this method.
 *
... some deleted ...
 *
 * @param r the runnable that has completed
 * @param t the exception that caused termination, or null if
 * execution completed normally
 */
protected void afterExecute(Runnable r, Throwable t) { }

Rather than keep track of all ThreadLocals, you could clear them all at once.

protected void afterExecute(Runnable r, Throwable t) { 
    // you need to set this field via reflection.
    Thread.currentThread().threadLocals = null;
}