当前位置:网站首页>Advanced multithreading: the role and implementation principle of volatile
Advanced multithreading: the role and implementation principle of volatile
2022-07-28 05:38:00 【A salted fish..】
List of articles
Tips : The following is the main body of this article ,Java The series of learning will be continuously updated
volatile The role of
1. volatile It can ensure the visibility of variables between multiple threads .
2. volatile prohibit CPU Perform instruction rearrangement during execution ( Memory barrier ) So as to ensure order and persistence .
3. volatile Atomicity is not guaranteed .
One 、volatile Achieve memory visibility
Memory visibility issues
Memory visibility issues : Under the condition that multiple threads share a data block , When a thread modifies data , Other threads are imperceptible . It will even be optimized by the compiler to the extent that it is completely invisible .
for example : When two threads operate on one memory at the same time , For example, read and write one by one , But when “ Write a thread ” When making changes ,“ Read thread ” May read the data before modification , You may also read the modified data , This is uncertain .
The invisible reason :
CPU In order to improve the data acquisition rate , Cache will be set .
In multicore CPU Next , Each core has its own exclusive cache for data access , Only after all processing , Will synchronize the data to main memory .
Therefore, some cores will read expired data .
volatile Principle
Simply speaking : When a shared variable is volatile When decorating , It ensures that the modified value is immediately updated to main memory , When there are other threads that need to read , It will go to memory to read new values .
When one is volatile When a keyword modified variable is modified by a thread , Other threads can immediately get the modified results .
When a thread is directed to volatile When a keyword modified variable writes data , Virtual opportunity forces it to be valued Refresh to main memory in .
When a thread is used by volatile When the keyword modifies the value , Virtual opportunity forces it Read from main memory .
How to achieve internal cache main memory synchronization ?
Cache consistency protocol (MESI): When CPU When writing data , If the variables of the operation are found, the variables are shared , That is, the working memory of other threads also has this variable , Then it will send a signal to inform others CPU The memory address of the variable is invalid . When other threads need to use this variable , If the memory address fails , Then they will re read the value in main memory .
The phenomenon :
import java.util.concurrent.TimeUnit;
public class Demo {
// Ensure memory visibility
public static volatile boolean flag = true;
static class Thread1 extends Thread {
@Override
public void run() {
while (flag) {
// Cycle all the time , wait for flag Be changed
}
System.out.println(" Threads 1 Find out flag Has been changed ...");
}
}
static class Thread2 extends Thread {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
System.out.println(" Threads 2 Revised flag Value ...");
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t2.start();
t1.start();
}
}
Two 、volatile Prohibit code reordering
Instruction reordering It is a means for compilers and processors to optimize programs efficiently , It can only ensure that the result of program execution is correct , However, there is no guarantee that the operation sequence of the program is consistent with the code sequence .
This does not pose a problem in a single thread , But there are problems in multithreading .
A very classic example is to add... To fields simultaneously in a singleton method voliate, To prevent instruction reordering .
private volatile static LazyModeV3 instance;
Steps of object instantiation :
memory = allocate(); // 1. Allocate object memory space
instance(memory); // 2. Initialize object
instance = memory; // 3. Set up instance Points to the memory address just allocated , here instance!=null
Steps after code reordering :
memory=allocate(); // 1. Allocate object memory space
instance=memory; // 3. Set up instance Points to the memory address just allocated , here instance!=null, But the object hasn't been initialized yet !
instance(memory); // 2. Initialize object
volatile Principle
volatile Prohibition of reordering is the use of
Memory barrier, To ensure order .
Memory barrier is a group CPU Instructions , It is used to realize the sequence restriction of memory operation .
Java When the compiler generates a series of instructions , stayThe memory barrier will be inserted in the appropriate positionTo prevent the processor from reordering instructions .
(1)volatile Two memory barriers are added before and after the variable write operation , To ensure that the previous write instructions and the subsequent read instructions are in order .
(2)volatile Insert two instructions after the read operation of the variable , Prevent subsequent read and write reordering .
3、 ... and 、volatile It doesn't support atomicity
Go straight to the code , Look at the phenomenon :
public class Test {
public static volatile int i = 0;
static class Thread1 extends Thread {
@Override
public void run() {
for (int j = 0; j < 1000000; j++) {
i ++;
}
}
}
static class Thread2 extends Thread {
@Override
public void run() {
for (int j = 0; j < 1000000; j++) {
i --;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1();
t1.start();
Thread2 t2 = new Thread2();
t2.start();
t1.join();
t2.join();
System.out.println(i);
// The result is a random number , explain volatile It doesn't support atomicity
}
}
summary :volatile Atomicity is not guaranteed , To ensure atomicity, we need to use a locking mechanism .
summary :
Tips : Here is a summary of the article :
The above is today's learning content , This article is about Java Multithreaded learning , In depth study of keywords volatile Function and principle of . After that, the learning content will be continuously updated !!!
边栏推荐
- Printf function of input and output function in C language
- openjudge:过滤多余的空格
- 【MySQL】MySQL时区问题、数据库时间相差8小时问题解决
- Openjudge: count the number of numeric characters
- (dark horse) MySQL beginner advanced notes (blogger lazy dog)
- Learning of image enhancement evaluation index -- structural similarity SSIM
- Invalid bound statement (not found): com.exam.mapper.UserMapper.findbyid
- Non functional test
- visio如何快速生成相同的图案,生成图像矩阵
- CentOS7安装MySQL5.7
猜你喜欢

使用navicat或plsql导出csv格式,超过15位数字后面变成000(E+19)的问题

Invalid bound statement (not found): com.exam.mapper.UserMapper.findbyid

自定义Json返回数据

冶金物理化学复习 --- 液 - 液相反应动力学

多模块打包:程序包:xxx不存在

2022 summer practice (PowerDesigner tutorial learning record) (first week)

IDEA使用dev-tool实现热部署

Distillation model diagram

ECCV22 最新54篇论文主图整理

regular expression
随机推荐
LocalDateTime去掉T,JSONField失效
【单例模式】懒汉模式的线程安全问题
mysql中使用list作为参数进行查询
导出excel,生成多个sheet页,并命名
多线程进阶:synchronized底层原理,锁优化、锁升级的过程
接口幂等性问题
openjudge:判断字符串是否为回文
Openjudge: find all substring positions
openjudge:找第一个只出现一次的字符
Scope, execution process and life cycle of bean
多线程进阶:锁的策略
蒙特卡罗方法求解圆周率π并用turtle画点,以及完成进度条问题
Writing methods of scientific research papers: add analysis and discussion in the method part to explain their contributions and differences
21 day SQL punch in summary
Openjudge: count the number of numeric characters
Personal summary of restful interface use
yandex robots txt
visio如何快速生成相同的图案,生成图像矩阵
JMeter related knowledge sorting
冶金物理化学复习 ---- 气固反应动力学

