2015-05-19 86 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(); 
}