当线程返回到线程池时,执行期间存储在ThreadLocal
中的内容会自动清除吗(这应该是预期的)?
在我的应用程序中,在某些执行期间将一些数据放入ThreadLocal
中,但如果下次使用相同的线程,则会在ThreadLocal
存储中找到过时的数据。
当线程返回到线程池时,执行期间存储在ThreadLocal
中的内容会自动清除吗(这应该是预期的)?
在我的应用程序中,在某些执行期间将一些数据放入ThreadLocal
中,但如果下次使用相同的线程,则会在ThreadLocal
存储中找到过时的数据。
ThreadLocal和ThreadPool除非你这样做,否则不会相互交互。
你可以创建一个单独的ThreadLocal用于存储所有需要保留的状态,并在任务完成时将其重置。你可以重写ThreadPoolExecutor.afterExecute(或beforeExecute)以清除你的ThreadLocal(s)。
来自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) { }
不必追踪所有的ThreadLocal,你可以一次性清除它们。
protected void afterExecute(Runnable r, Throwable t) {
// you need to set this field via reflection.
Thread.currentThread().threadLocals = null;
}
ThreadPoolExecutor
使用了一些线程本地变量,会怎么样? - ZhongYu不行。原则上,将某些东西放入线程本地的人应该负责清除它。
threadLocal.set(...);
try {
...
} finally {
threadLocal.remove();
}