gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:21:15 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com