There is a method in threads that is frequently called by everyone, and that is ThreadLocal. However, ThreadLocal will also encounter more difficult problems in memory processing, and some memory leaks will always occur. This article will use a leakage example to analyze for everyone, and also help you understand some situations in the leakage, and propose ThreadLocal corresponding solutions.
1. Leakage examples
Static inner class Entry of ThreadLocalMap:
static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }
ThreadLocalMap uses the static internal class Entry to implement <k, v> storage, and Entry inherits the WeakReference class, so the key in ThreadLocalMap is actually a weak reference to ThreadLocal.
Precisely because ThreadLocalMap uses the weak reference of ThreadLocal as the key, when this ThreadLocal has no external strong reference, it will be GC. At this time, an Entry with a null key will appear in ThreadLocalMap. Of course, the value of this Entry will never be accessed.
In this case, if the current working thread has not ended, then the value with a null key is strongly referenced by Entry, and Entry is strongly referenced by the ThreadLocalMap of the current thread, causing this value to never be GCed, causing a memory leak.
2. Solution
ThreadLocalMap's cleanSomeSlots() and expungeStaleEntry() methods can clear values with null keys. In the set(), get(), and remove() methods of ThreadLocal, cleanSomeSlots() or expungeStaleEntry() will be called to clear all values with null keys in the ThreadLocalMap.
The above is the solution to the java ThreadLocal memory leak. Of course, this can only play a certain role in memory leaks. After all, it is just a kind of clarity and there is no guarantee that it will not occur .