What is the cleanest way to dispose of ThreadLocal
variables so that they are subject to garbage collection? I read from the docs that:
...after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
But sometimes threads can be pooled or are not expected to die. Does the ThreadLocal#remove()
method actually make the value subject to garbage collection?
ThreadLocal.remove()
is indeed removing a reference to the value... and if there is no more other living reference to it : the value will be soon garbage collected.
When the thread died, the thread is removed form the GC-root... therefore the entry for the thread in the ThreadLocal is subject to GC... therefore the value for this entry in the ThreadLocal is subject to GC. But once again, if you have another living ref to the value : it won't be garbage collected.
If the thread is reused (because part of a pool or ...) : it is important to call remove()
so that the value can be garbage collected, but also to avoid unexpected behavior when a new job is executed on a recycled thread (the new job don't need to know the value used by the previous job)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments