Reputation: 381
I don't understand Why ThreadLocalMap.Entry extends WeakReference.
What's the benefit of doing this?
After all, theadlocal.remove()
must be called when necessary.
What if we just make ThreadLocalMap.Entry as an ordinary struct like
{key, value}, and the key is a strong reference to ThreadLocal?
Upvotes: 3
Views: 718
Reputation: 71
Imagine this. You use thread pools in your program. To avoid concurrency errors, you use ThreadLocal frequently. When a thread completes the task, you want the GC to release the ThreadLocal object. So set it to null in your thread.
OK. Now there are two situations. A and B.
A: Suppose there is a strong reference to ThreadLocal in ThreadLocalMap. The ThreadLocal object is not recycled. We have to wait until the thread object is recycled before we can recycle the ThreadLocal object. The bad news, however, is that thread pools often reuse Thread objects that have already been created, rather than reclaiming them after the thread completes its task. As a result, we have more and more ThreadLocal objects that can't be recycled until the JVM has no more memory available and throws OutOfMemoryError, and our program crashes.
B: Because Entry inherits WeakReference, the reference to ThreadLocal object in TreadLocalMap is a weak reference. When the thread completes the task, we set the reference of ThreadLocal in the thread to null. At this point, the ThreadLocal object has only one weak reference in ThreadLocalMap. When GC scans the ThreadLocal object and finds that it has only one weak reference, it ignores the weak reference and recycles the ThreadLocal object. This is what we want. And this is why Entry extends WeakReference.
I hope my answer can help you understand better ^_^
Upvotes: 4