Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; 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).
Mohamed Sanaulla | My Blog | Author of Java 9 Cookbook | Java 11 Cookbook
Mohamed Sanaulla wrote:From the Documentation for the ThreadLocal
and the ThreadLocal instance is accessible;
Martin Vajsar wrote:
Edit: thread locals should really get cleared when the thread terminates, not when it is garbage collected. I had thought otherwise.
Sergey Alaev wrote:
This is not the case - i've deleted reference to ThreadLocal instance as you can see.
Henry Wong wrote:
On the other hand, the Thread object needs to be unreachable
Stephan van Hulst wrote:I may be wrong, but isn't a thread always reachable as long as it's alive?
Martin Vajsar wrote:
Stephan van Hulst wrote:I may be wrong, but isn't a thread always reachable as long as it's alive?
It certainly is, but on the other hand, it may be reachable long after it had terminated. The thread locals are cleared when it terminates, not when it becomes unreachable.
Henry Wong wrote:
I now think that the value should become unreachable, when the thread local becomes unreachable too -- maybe it would be a good idea to modify the test harness to call system.gc() a few times (or in a loop). And see if it eventually disappears.
Henry
Martin Vajsar wrote:
It should not be so. Firstly, the documentation states that values are kept while the thread is alive, not while it is referenced, and secondly, the exit() method in Thread that is called by the JVM when thread terminates clears the local values of the thread, as can be seen in the JDK source.
Sergey Alaev wrote:
It will not disappear because as i've written above it is hard-referenced to current Thread instance.
Question now is WHY it is hard-referenced
Because i cant believe it is a bug.
Henry Wong wrote:I forget that weak hash maps needs to be used in order to clear entries. Only the key is weak. And there isn't a thread that will clear them periodically. After the GC, try changing your test to create another thread local object, and using it; maybe that will trigger the Thread's weak hashmap to clear it's entries. And of course, GC again.