2015-05-19 14 views
7

I contenuti archiviati nella memoria ThreadLocal durante un'esecuzione vengono cancellati automaticamente quando il thread viene restituito a ThreadPool (come previsto) ??L'oggetto ThreadLocal verrà cancellato dopo che il thread è stato restituito al pool di thread?

Nella mia applicazione sto mettendo alcuni dati in ThreadLocal durante alcune esecuzione, ma se la prossima volta viene utilizzato lo stesso filo, quindi mi sto trovando i dati obsoleti in ThreadLocal stoccaggio.

+2

Non ti risponde alla tua domanda? Dici: "se viene usato lo stesso thread, allora sto trovando dati obsoleti". Allora, qual è la tua domanda allora? – GhostCat

+0

Che pool di thread? – erickson

risposta

6

ThreadLocal e ThreadPool non interagiscono tra loro a meno che non lo facciate.

Quello che si può fare è un singolo ThreadLocal che memorizza tutto lo stato che si desidera mantenere e deve essere ripristinato al termine dell'attività. È possibile ignorare ThreadPoolExecutor.afterExecute (o BeforeExecute) per cancellare il tuo ThreadLocal (s)

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

Invece di tenere traccia di tutte le ThreadLocals, li si potrebbe cancellare in una sola volta.

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

amico ... e cosa succede se 'ThreadPoolExecutor' utilizza alcune variabili locali del thread. – ZhongYu

3

No. In linea di principio, chiunque mettere qualcosa in discussione locale dovrebbe essere responsabile per cancellarlo

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