Will the ThreadLocal object be cleared after the thread returns to the thread pool?

Will the content stored in the ThreadLocal repository at runtime be automatically cleared when the thread returns to ThreadPool (as expected)?

In my application, I put some data in ThreadLocal during some execution, but if the same Thread is used next time, then I find outdated data in the ThreadLocal repository.

+7
java multithreading threadpool thread-local
source share
2 answers

ThreadLocal and ThreadPool do not interact with each other if you do not.

What you can do is the only ThreadLocal that saves all the state you want to save and have it reset when the task completes. You can override ThreadPoolExecutor.afterExecute (or beforeExecute) to clear ThreadLocal (s)

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

Instead of tracking all ThreadLocals, you can clear them immediately.

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

Not. As a principle, whoever puts something in the local thread should be responsible for cleaning it.

 threadLocal.set(...); try { ... } finally { threadLocal.remove(); } 
+3
source share

All Articles