本文介绍了线程返回线程池后,是否将清除ThreadLocal对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Will the contents that are stored in the ThreadLocal storage during an execution be cleared automatically when the thread is returned to ThreadPool (as would be expected) ??

在我的应用程序中,我将在某些执行过程中将一些数据放入ThreadLocal中,但是如果下次使用同一线程,那么我将在ThreadLocal存储中发现过时的数据.

In my application I am putting some data in ThreadLocal during some execution but if next time the same Thread is being used, then I am finding the obsolete data in ThreadLocal storage.

推荐答案

除非您这样做,否则ThreadLocal和ThreadPool不会相互影响.

The ThreadLocal and ThreadPool don't interact with one another unless you do this.

您可以做的是一个单独的ThreadLocal,它存储您要保留的所有状态,并在任务完成时将其重置.您可以重写ThreadPoolExecutor.afterExecute(或beforeExecute)以清除您的ThreadLocal

What you can do is a a single ThreadLocal which stores all the state you want to hold and have this be reset when the task completes. You can override ThreadPoolExecutor.afterExecute (or beforeExecute) to clear your ThreadLocal(s)

来自ThreadPoolExecutor

From 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) { }

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

Rather than keep track of all ThreadLocals, you could clear them all at once.

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

这篇关于线程返回线程池后,是否将清除ThreadLocal对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 19:44