作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
当线程返回到 ThreadPool 时,执行期间存储在 ThreadLocal
存储中的内容是否会自动清除(如预期的那样)??
在我的应用程序中,我在某些执行期间将一些数据放入 ThreadLocal
但如果下次使用相同的线程,那么我会在 ThreadLocal
中找到过时的数据存储。
最佳答案
除非您这样做,否则 ThreadLocal 和 ThreadPool 不会相互交互。
您可以做的是一个单一的 ThreadLocal,它存储您想要保持的所有状态,并在任务完成时重置它。您可以覆盖 ThreadPoolExecutor.afterExecute(或 beforeExecute)以清除您的 ThreadLocal(s)
来自线程池执行器
/**
* 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;
}
关于java - 线程返回线程池后ThreadLocal对象会被清空吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328437/
我是一名优秀的程序员,十分优秀!