线程返回线程池后是否清除ThreadLocal对象?

Rah*_*hak 12 java multithreading thread-local threadpool

ThreadLocal执行期间存储在存储中的内容是否会在线程返回ThreadPool时自动清除(如预期的那样)?

在我的应用程序中,我ThreadLocal在一些执行期间放入一些数据,但如果下次使用相同的Thread,那么我在ThreadLocal存储中找到过时的数据.

Pet*_*rey 11

除非您这样做,否则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) { }
Run Code Online (Sandbox Code Playgroud)

您可以一次清除所有ThreadLocals,而不是跟踪所有ThreadLocals.

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

  • 如果`ThreadPoolExecutor`使用一些线程局部变量,该怎么办? (2认同)

Zho*_*gYu 9

不是.作为一个原则,任何人在本地线程中放置一些东西应该负责清除它

threadLocal.set(...);
try {
  ...
} finally {
  threadLocal.remove();
}
Run Code Online (Sandbox Code Playgroud)