Underlying Implementation Principles
The implementation principle of ThreadLocal is that each Thread maintains a ThreadLocalMap mapping table. The key of the mapping table is the instance of ThreadLocal, and the weak reference of ThreadLocal is used. The value of the mapping table is the Object to be stored. The following diagram shows the reference relationships between these objects, with solid arrows representing strong references and hollow arrows representing weak references.
Memory leak problem
As you can see from the above figure, if a ThreadLocal has no external strong references, the ThreadLocal will definitely be collected when garbage collection occurs. This results in null key entries in ThreadLocalMap, no external access to the value of these null key entries, and a strong reference chain if the current thread is always alive: Thread Ref -> Thread -> ThreaLocalMap -> Entry -> Value. As a result, the Object corresponding to the value cannot be reclaimed, resulting in memory leakage.
The get, set, and remove methods of ThreadLocal remove all values with a null key. However, a memory leak can occur when a ThreadLocal get or set method is used. A null value will not be cleared if the get, set, or remove methods are not called thereafter.
The solution is to call its remove() method every time a ThreadLocal is used to remove data, or as the JDK recommends, make the ThreadLocal variable private static so that a strong reference to ThreadLocal always exists. This ensures that the Entry value can be accessed through ThreadLocal’s weak reference at any time, and then erased.
Past highlights
-
High concurrency programming -AQS in-depth analysis
-
High concurrency programming -CountDownLatch in-depth parsing
-
High concurrency programming -CAS in-depth parsing
-
High concurrency programming -CyclicBarrier in-depth parsing
-
High concurrency programming -Semaphore in-depth parsing
-
High concurrency programming -ReentrantLock Fair lock in-depth parsing
-
High concurrency programming -ReentrantLock Deep parsing of unfair locks
-
High concurrency programming -ReentrantReadWriteLock In-depth parsing
-
High concurrency programming -Condition in-depth parsing
-
High concurrency programming -synchronized in-depth parsing
-
High concurrency programming -synchronized deep parsing deep dig
-
High concurrency programming – lock optimization details
-
High concurrency programming – Volatile details
-
High concurrency programming -happens-before
-
High concurrency programming -HashMap in-depth parsing
Feel harvest, invite attention, like, forward.