当前位置:网站首页>Why can ThreadLocal achieve thread isolation?
Why can ThreadLocal achieve thread isolation?
2022-07-28 08:43:00 【JavaShark】
about ThreadLocal We're all familiar , Its function is like its name —— To hold 「 Thread local 」 Variable .
First, feel it through a small example :
private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) throws Throwable {
Thread threadOne = new Thread(()->{
threadLocal.set("ThreadOne:" + Thread.currentThread().getName());
log.info(" Threads One The local variable value is :{}", threadLocal.get());
threadLocal.remove();
log.info(" Threads One remove The post local variable value is :{}", threadLocal.get());
});
Thread threadTwo = new Thread(()->{
threadLocal.set("ThreadTwo:" + Thread.currentThread().getName());
log.info(" Threads Two The local variable value is :{}", threadLocal.get());
});
threadOne.start();
threadTwo.start();
}Running results :
Threads One The local variable value is :ThreadOne:Thread-0
Threads One remove The post local variable value is :null
Threads Two The local variable value is :ThreadTwo:Thread-1
OK, In terms of effect ,ThreadLocal It is indeed thread isolated , that , How does it achieve thread isolation ? Now let's dig up the source code , See how it does it :
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}set() The logic of the method is as follows :
- Get the current thread
- Get a from the current thread ThreadLocalMap object
- If map Not for null Save
- If map by null Then create a map
getMap() and createMap() What have the methods done ? Let's go in and have a look :
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}After entering the two methods, I found , No matter which branch you take , Finally, the value is saved to the current thread threadLocals Properties of the .
see Thread Class source code , You will find that there is a threadLocals attribute , And the initial value is null, The type of ThreadLocal.ThreadLocalMap.
public class Thread implements Runnable {
// ...
ThreadLocal.ThreadLocalMap threadLocals = null;
// ...
}Here we are , We found out , original ThreadLocal Is to put the object we want to pass into the current thread threadLocals Properties of the . That is, each thread is using ThreadLocal When you save an object , In fact, the object is placed in the current thread instance object threadLocals Attributes inside . In this way, threads are naturally independent of each other .
I want to see others get() Method :
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}ThreadLocal Of get() The method is actually the same as set() The method logic is very similar , From the current thread of threadLocals Property , If the property is null, So initialize .
When the thread ends , Will call the current thread instance exit() Method , take threadLocals Set to null, So that the garbage collector can recycle it .
// THread Methods in class
private void exit() {
// ...
threadLocals = null;
// ...
}Last , One thing needs special attention : run out ThreadLocal Be sure to call manually remove() Method , Otherwise, dirty data or even memory leaks may occur .
Why? ? The above does not mean that when the thread ends , Will threadLocals Set as null Do you ?
Yes , At the end of the thread , Do clean up .
but , What if the thread never ends ? What if threads will be reused ? For example, thread pool is used .
therefore , Use ThreadLocal Be sure to manually remove().
边栏推荐
- opencv+paddle orc 识别图片提取表格信息
- Leetcode/ sum of two numbers in a sorted array
- 客户至上 | 国产BI领跑者,思迈特软件完成C轮融资
- 解决:IndexError: index 13 is out of bounds for dimension 0 with size 13
- MySQL怎么查询可以同时判断多个字段值是否存在
- 一篇文章搞懂数据仓库:元数据分类、元数据管理
- 说透缓存一致性与内存屏障
- How does QT delete all controls in a layout?
- Js继承方法
- sparksql 与flinksql 建表 与 连表记录
猜你喜欢

阿里技术四面+交叉面+HR面,成功拿到offer,双非本科进不了大厂?

uniapp---- 获取当前位置的经纬度等信息的详细步骤(包含小程序)

半桥BUCK电路—记录篇

学术界爆火的类脑智能,啥时候能落地?来听行业大咖怎么说丨量子位·对撞派 x 时识科技...

The current value of uniapp's swiper dynamic setting does not take effect solution

【OpenCV】生成透明的PNG图像

uniapp的swiper动态设置current值不生效解决办法

Day112. Shangyitong: Mobile verification code login function

Unity切换到另一个场景的时候,发现该场景变暗了

Smartbi of smart smart smart software completed the c-round financing and accelerated the domestic Bi into the intelligent era
随机推荐
Wechat applet - wechat applet browsing PDF files
When will brain like intelligence, which is popular in academia, land? Let's listen to what the industry masters say - qubits, colliders, x-knowledge Technology
pyspark更改列顺序存入iceberg数据库
GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览
sparksql 与flinksql 建表 与 连表记录
Day112.尚医通:手机验证码登录功能
49-OpenCv深入分析轮廓
PHP Basics - PHP uses PDO
【OpenCV】生成透明的PNG图像
谷歌 Material Design 的文本框为什么没人用?
oracle sql 问题
postgresql查询【表字段类型】和库中【所有序列】
网络安全漏洞分析与漏洞复现
Get the clicked line number in qtablewidget
2022 Niuke multi school second problem solving Report
[soft test software evaluator] 2013 comprehensive knowledge over the years
MySQL how to add users and set permissions?
HCIP第九天_BGP实验
‘全局事件总线’&‘消息订阅与发布’
Pyflink connecting iceberg practice