当前位置:网站首页>ThreadLocal thread safety example and its principle
ThreadLocal thread safety example and its principle
2022-07-19 05:08:00 【mabo_ [email protected]】
Tips : When multiple threads access the same object , If you don 't have to consider the scheduling and alternate execution of these threads in the runtime environment , There's no need for extra synchronization , Or in any other way , The behavior of calling this object can get the correct result , So this object is thread safe
ThreadLocal Is to trade space for time ,synchronized The key word is to trade time for space .
ThreadLocal Thread safety example and its principle
Preface
Thread safety is a concept in computer program code when multithreading . In a program that runs in parallel with multiple threads that share data , Thread safe code can ensure that all threads can execute normally and correctly through synchronization mechanism , There will be no data pollution and other accidents .
When multiple threads access the same object , If you don 't have to consider the scheduling and alternate execution of these threads in the runtime environment , There's no need for extra synchronization , Or in any other way , The behavior of calling this object can get the correct result , So this object is thread safe .
Tips : The following is the main body of this article , The following cases can be used for reference
One 、 Example
The following example illustrates the process of two threads operating on the same object , Thread safety and thread insecurity
ThreadLocal Thread safety example
package com.mabo;
import java.util.concurrent.TimeUnit;
public class TheadLocalTest {
private static ThreadLocal<Integer> threadLocalStudent = new ThreadLocal<>();
private static int a=0;
static {
threadLocalStudent.set(a);
}
public static void main(String[] args) {
// Simply write an example of testing thread isolation
// raw material : 1 individual ThreadLocal Variable of type 2 Threads
// Expected results : Thread one set The variable of Thread two get Less than !
new Thread(()->{
a=2;
threadLocalStudent.set(a);
System.out.println(Thread.currentThread()+" Thread saved objects :"+threadLocalStudent.get());
try {
// details !!! Sleep for a while before get Avoid error .
// It can be seen that this is a very rigorous test Demo
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+" The value of is "+threadLocalStudent.get());
}).start();
new Thread(()->{
a=6;
threadLocalStudent.set(a);
System.out.println(Thread.currentThread()+" Thread saved objects :"+threadLocalStudent.get());
try {
// details !!! Sleep for a while before get Avoid error .
// It can be seen that this is a very rigorous test Demo
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+" The value of is "+threadLocalStudent.get());
}).start();
}
}
Execution results 
Non thread safe examples
package com.mabo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
public class Test {
private static int a=0;
/** * @Description : test * When the current object is operated by another thread during the operation of one thread , Thread unsafe * @Author : mabo */
public static void main(String[] args) {
new Thread(()->{
a=2;
System.out.println(Thread.currentThread()+" Thread saved objects :"+a);
try {
// details !!! Sleep for a while before get Avoid error .
// It can be seen that this is a very rigorous test Demo
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+" The value of is "+a);
}).start();
new Thread(()->{
a=6;
System.out.println(Thread.currentThread()+" Thread saved objects :"+a);
try {
// details !!! Sleep for a while before get Avoid error .
// It can be seen that this is a very rigorous test Demo
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+" The value of is "+a);
}).start();
}
}
Execution results 
Two 、ThreadLocal Thread safety principle
Thread safety principle
You can see ThreadLocal When you operate the value, you get the current thread ThreadLocalMap object , Then set the value into this object , In this way, different threads get different ThreadLocalMap, Then saving or modifying values will only affect the current thread , This ensures thread safety .
Source code is as follows
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
Memory leak
because Thread Contains variables ThreadLocalMap, therefore ThreadLocalMap And Thread The life cycle of is the same , If none of them are deleted manually key, Will lead to memory leaks .
But using weak references can provide more security : Weak reference ThreadLocal No memory leaks , Corresponding value The next time ThreadLocalMap call set(),get(),remove() Will be cleared when .
therefore ,ThreadLocal The root cause of the memory leak is : because ThreadLocalMap The life cycle of Thread As long as , If the corresponding is not deleted manually key Will cause memory leaks , Not because of weak references .
ThreadLocal Correct usage
After each use ThreadLocal It's called remove() Method to clear data
take ThreadLocal Variables are defined as private static, It's always there ThreadLocal A strong reference to , It can also guarantee to pass at any time ThreadLocal A weak reference to Entry Of value value , And then get rid of .
3、 ... and 、 Other thread safe collections
Vector( Not recommended )
Vector and ArrayList similar , Is a variable length array , And ArrayList The difference is ,Vector It's thread safe , It gives almost all public Methods are added sychronized keyword . Due to locking, the performance is reduced , When concurrent access is not required , This forced synchronization is redundant , So few people are using it now .
HashTable
HashTable and HashMap similar , The difference is HashTable It's thread safe , It is also almost for all public Methods are added sychronized keyword , Another difference is :HashTable Of K, V It can't be null, however HashMap Sure .
Collections Packing method
because ArrayList and HashMap Good performance , But not thread safe , therefore Collections Tool classes provide corresponding wrapper methods to wrap them into corresponding thread safe collections :
List<E> synchronizedList = Collections.sychronizedList(new ArrayList<E>());
Set<E> sychronizedSet = Collections.sychronizedSet(new HashSet<E>());
Map<K, V> synchronizedMap = Collections.sychronizedMap(new HashMap<K, V>());
Collections A thread safe wrapper class is declared for each collection , The lock object is added on the basis of the original set , Each method in the collection is synchronized through this lock object
ConcurrentHashMap( Multiple barrels , Lock part )
ConcurrentHashMap and HashTable Are thread safe collections , The difference between them is mainly the difference in locking granularity .HashTable The method of locking is to add... To each method synchronized keyword , In this way, the whole object is locked . and ConcurrentHashMap There are finer grained locks .
stay JDK1.8 Before ,ConcurrentHashMap Add a section lock , namely Segment, Every Segment Contains the whole table Part of , In this way, the concurrent operations between different segments do not affect each other .
JDK1.8 After that, further improvements were made , To cancel the Segment, Directly in table Lock the element , Lock each row , It further reduces the probability of concurrent conflict .
CopyOnWriteArrayList and CopyOnWriteArraySet
For the part involving data modification , Will use ReentrantLock Locking operation , And will modify or add elements , By copying , Add to the array , Finally, modify the reference of the array to the newly copied array . Read the array directly when reading , No need to acquire lock .
Four 、Java Concurrent programming 12 The specific implementation of the lock
Click the following link to view
Java Concurrent programming 12 The specific implementation of the lock – Click here to jump to
summary
ThreadLocal Is to trade space for time ,synchronized The key word is to trade time for space .
How to use , It needs to be used reasonably according to needs
版权声明
本文为[mabo_ [email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207170502056604.html
边栏推荐
猜你喜欢

pygame-飞机大战1.0(步骤+窗口无响应问题)

Modelarts second training notes

First training notes of moderlarts

基于SSM框架的考勤签到请假系统

How to upload qiniu cloud

租用服务器,以及部署在pycharm专业版上的pytorch环境训练yolov5模型教程服务器环境安装库文件:

泰迪杯A题完整版 优化更新(4/23)

elment-ui使用方法

The code of yolov5 model for pest identification in Title A of the 10th Teddy cup data mining challenge (has been run through, original works, continuously updated)

Hire the server, and the pytorch environment training yolov5 model tutorial deployed on pycharm professional edition. Server environment installation library file:
随机推荐
Simple use of directexchange switches.
【C语言—零基础_学习_复习_第五课】基本运算符的运算性质
POC——DVWA‘s SQL Injection
Travel data acquisition, data analysis and data mining [2022.5.30]
学习C语言的第四天
IDL 6S查找表
Modelarts second training notes
. SH scripting
学习C语言的第五天
用户登录-以及创建验短信证码
图片上传的逻辑
小程序editor富文本编辑使用及rich-text解析富文本
MySQL optimization
【C语言—零基础第十四课】变量的作用域与存储类
User management - restrictions
Encryption and decryption
Wechat docking mechanism memo
C语言初学者之初识代码专项练习
Redis installation
获取数组中对象内部的数值最大与最小值多功能版及点名系统完整版并展示效果