Article Directory
1 Basic knowledge
1.1 Four references of strong, weak, and virtual
[Overall structure]
[Strong reference]
[Soft reference]
[Weak reference]
[Phantom reference]
2 The benefits of ThreadLocal
3 ThreadLocal source code analysis
3.1 ThreadLocal memory leak problem
3.2 Why ThreadLocal uses weak references
3.3 Clean up expired Entry
expungeStaleEntry
4 ThreadLocal usage suggestions
【initialization】
ThreadLocal<String> t1 = ThreadLocal.withInitial(() -> "hello");
[declare as static]
It is recommended to modify ThreadLocal as static
ThreadLocal implements thread isolation not in itself, but in ThreadLocalMap, so ThreadLocal can be initialized only once and storage space allocated only once. It does not need to be initialized multiple times as a member variable.
After use, you need to display and call remove