ThreadLocal of JUC

1 Basic knowledge

1.1 Four references of strong, weak, and virtual

[Overall structure]
insert image description here
[Strong reference]
insert image description here
[Soft reference]
insert image description here
[Weak reference]
insert image description here
insert image description here
[Phantom reference]
insert image description here
insert image description here

2 The benefits of ThreadLocal

insert image description here

3 ThreadLocal source code analysis

insert image description here
insert image description here
insert image description here

3.1 ThreadLocal memory leak problem

insert image description here
insert image description here
insert image description here

3.2 Why ThreadLocal uses weak references

insert image description here
insert image description here

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

Guess you like

Origin blog.csdn.net/kaikai_sk/article/details/131503129