2015-05-19 48 views
7

将线程返回到ThreadPool时,会自动清除在执行期间存储在ThreadLocal存储器中的内容(如预期的那样)?ThreadLocal对象在线程返回到线程池之后会被清除吗?

在我的应用程序中,我在一些执行过程中将一些数据放在ThreadLocal中,但如果下一次使用相同的线程,则我在ThreadLocal存储中找到过时的数据。

+2

你不回答自己的问题?你说:“如果使用相同的线程,那么我找到了过时的数据”。那么,你的问题是什么呢? – GhostCat

+0

什么线程池? – erickson

回答

6

除非您这样做,否则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) { } 

而不是把所有ThreadLocals的轨道,你可以同时清除它们。

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

伙计......如果'ThreadPoolExecutor'使用某些线程局部变量会怎么样。 – ZhongYu

3

号作为一个原则,谁装上去线程局部应负责将其清除

threadLocal.set(...); 
try { 
    ... 
} finally { 
    threadLocal.remove(); 
}