java - 线程返回线程池后ThreadLocal对象会被清空吗?

标签 java multithreading threadpool thread-local

当线程返回到 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/

相关文章:

java - 在 Android 应用程序中隐藏 API URL - 2018

java - 这个结构线程安全吗?

c# - 如何从 Process.GetCurrentProcess().Threads 获取托管线程

java - java线程池执行器如何处理中断的线程

java - JVM 是生成字节码还是运行字节码?

java - java中如何将统计数据写入滚动文件

java - 告诉eclipse重新加载环境变量

python - Tornado 与 ThreadPoolExecutor

.net - 调试 I/O 完成线程泄漏

multithreading - C++11线程池——带输入参数的任务