当前位置:网站首页>ThreadLocal thread variable
ThreadLocal thread variable
2022-06-29 08:32:00 【Envy ˇ】
Catalog
ThreadLocal Implementation principle analysis
ThreadLocal Memory leak problem
ThreadLocal What is it? ?
ThreadLocal Allows us to create thread private variables , This variable is invisible to other threads ,ThreadLocal A copy of the variable is created in each thread , Each thread can access its own private thread variables , The code example is as follows :
public class ThreadLocalDemo {
// Create a ThreadLocal object , Used to copy and save a variable for each thread , Implement thread closure
private static ThreadLocal<Integer> localNum = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 1;
}
};
public static void main(String[] args) {
// Threads 0
new Thread(){
@Override
public void run() {
localNum.set(1);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
localNum.set(localNum.get()+10);
System.out.println(Thread.currentThread().getName()+":"+localNum.get());//11
}
}.start();
// Threads 1
new Thread(){
@Override
public void run() {
localNum.set(3);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
localNum.set(localNum.get()+20);
System.out.println(Thread.currentThread().getName()+":"+localNum.get());//23
}
}.start();
System.out.println(Thread.currentThread().getName()+":"+localNum.get());//0
}
}
As mentioned above , You count main Thread and the new two threads , A total of three threads , Each thread contains its own private variables , Here we set the value 1 , set() and get() Method is used to set and obtain values , The results are as follows :

ThreadLocal Implementation principle analysis
ThreadLocal Is a generic class , Can accept any type of object , It maintains a ThreadLocalMap The static inner class of , What we use get(), set() In fact, they all come from this class , Each time, a... Is created for the current thread ThreadLocalMap object , Used to record private values

First look at set() Method
public void set(T value) {
// Get the current thread
Thread t = Thread.currentThread();
// Get the current thread map
ThreadLocalMap map = getMap(t);
if (map != null)
// Setting value exists
map.set(this, value);
else
// Create if it does not exist
createMap(t, value);
}void createMap(Thread t, T firstValue) {
//threadLocals This is the property map
t.threadLocals = new ThreadLocalMap(this, firstValue);
}Next is get() Method
public T get() {
// Get the current thread
Thread t = Thread.currentThread();
// Get the corresponding... Of the current thread map
ThreadLocalMap map = getMap(t);
// If already map
if (map != null) {
// Value operation , Get the corresponding Entry
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
// No, map, Then create and initialize a map
return setInitialValue();
}private T setInitialValue() {
//initialValue() Method value by null
T value = initialValue();
// Get the current thread to create the corresponding map
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}ThreadLocal It can be understood as right ThreadLocalMap Encapsulation
ThreadLocal Memory leak problem
stay ThreadLocalMap in , Use ThreadLocal As a weak reference to key

In this case , If one ThreadLocal When there is no external strong reference , that key Destined to be GC Recycling , This leads to ThreadLocalMap in key by null , and value There are also strong reference chains
A thread can have multiple threads at the same time ThreadLocal, If as a weak reference key After being recycled , value Can't be recycled yet , So this leads to this ThreadLocal The life cycle of is as long as this thread ( Because after the thread is executed, this value The chain of strong references will break ), If the thread never ends , Stacked value It has never been recycled , Then there will be a memory leak problem
The solution here is : After each use ThreadLocal It is called after remove() Method to clear data
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}Here, let's take another look key As the difference between strong and weak references
If key As a strong reference , Then its life cycle is as long as that of a thread , There are stable strong reference chains , Cannot be recycled , Memory leak problem , And if it's a weak reference , GC Will automatically recycle them , In the subsequent remove() The method can also be better recycled value , So we will generally ThreadLocal Designed to private static Of , Use... After use remove() Method to delete them manually
边栏推荐
- Verilog first experience
- 华为设备配置小型网络WLAN基本业务
- 802.11--802.11n协议 PHY
- Binary search tree
- Interprocess communication (IPC)
- 服装产业发展趋势|供应链|智能制造
- New spark in intelligent era: wireless irrigation with Lora wireless transmission technology
- 各种级数(调和、几何)总结
- Oracle-子查询
- Open an account to buy funds. Is it safe to open an account through online funds-
猜你喜欢

A review of visual SLAM methods for autonomous driving vehicles

华为设备配置小型网络WLAN基本业务

Notice on organizing the second round of the Northwest Division (Shaanxi) of the 2021-2022 National Youth electronic information intelligent innovation competition

消息中间件:pulsar

Introduction to taro

Mongodb- connect to the database using the mongo/mongosh command line

各种级数(调和、几何)总结

Friends, static keywords, static methods, and relationships between objects

A review of visual SLAM methods for autonomous driving vehicles

Binary search tree
随机推荐
为什么两个执行很快的SQL,union之后特别慢
关于#sql#的问题:创建一个名为View_XB视图,功能是①如果有重名的视图先删除后创建②显示XSB表中本班级的男女生各有多少人,并添加检查约束
目标跟踪【单目标跟踪(VOT/SOT)、目标检测(detection)、行人重识别(Re-ID)】
solidity部署和验证代理合约
语音处理工具:sox
Application of mediastreamer2 and GStreamer in embedded field
Write time replication of hugetlbfs
[domain penetration authorization] cve-2020-1472 Netlogon privilege escalation vulnerability
Should product managers learn from ink knife or Axure?
sql语句concat搜索不出结果
Mutex mutex
开户买基金,通过网上基金开户安全吗?-
Notes mosaïque
x86和x64的区别
In PHP version 7.1.13, it is found that floating-point data passes through JSON during use_ There will be precision problems after encode
dcase_util教程
NLP标注工具:Label Studio实现多用户协作打标
Set up Jenkins environment and automatically associate packaged project jars for automatic release
Django - installing mysqlclient error: mysqlclient 1.4.0 or newer is required; you have 0.9.3
NP3 formatted output (I)