I have this three questions:
1.Is there a way to clean ThreadLocal's data when the Thread's task is done.
2.How about when the thread is in ThreadPool.
3.How can I know a Thread is reused and given back to the ThreadPool.
I have this three questions:
1.Is there a way to clean ThreadLocal's data when the Thread's task is done.
2.How about when the thread is in ThreadPool.
3.How can I know a Thread is reused and given back to the ThreadPool.
Ad 1) To 'clean' the data of a ThreadLocal
, simply call ThreadLocal#remove()
.
Ad 2) ThreadLocal
s don't behave differently if accessed by a Thread
from a thread pool.
Ad 3) You can't. It is highly dependent on the thread pool you use. Some thread pools offer a way to hook into, others don't.
Sidenote: Usually it shouldn't be of any interest, if a Thread
of a thread pool is newly created or reused or given back, except when you want to extend an existing thread pool.
Removing thread local variables from thread pools is something widely applied in application containers. I answered a question on this topic here: Why do some webservers complain about memory leaks they create?
The easiest way to get rid of thread local variables is getting rid of the tread holding them. The only other way of cleaning out these variables would be reflectively accessing the thread's thread local map which basically represents a map where thread ids point to values which is how thread local pointers are implemented. There is no JVM magic involved when using thread locals. In the end its just a map which can be cleared. (In the linked article, I explain why this is often a bad idea when sharing threads.) The reflective access will however be much more expensive then renewing the thread.
However, you might just reconsider your design. Guava offers a cache which can be built with soft references. This way, you could build a proper cache where your keys could be made up by a thread specific UUID. I do not know your application well enough to give you further advice here. Using thread locals is almost always wrong, though.
Is there a way to clean ThreadLocal's data when the Thread's task is done.
You can explicitly set null in the task code.
How about when the thread is in ThreadPool.
Same as 1.
How can I know a Thread is reused and given back to the ThreadPool.
You can use ThreadLocal for that as well. But you shouldn't need to distinguish new and reused threads.