当前位置:网站首页>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 !!!
边栏推荐
猜你喜欢

ByteBuffer.position 抛出异常 IllegalArgumentException

SSLError

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

repackag failed: Unable to find main class

Distillation model diagram

Tomato timing dimming table lamp touch chip-dlt8t10s-jericho

架构设计思考之一(SSO设计)

Scope, execution process and life cycle of bean

How Visio can quickly generate the same pattern and image matrix

Eccv2022 | 29 papers of Tencent Youtu were selected, including face security, image segmentation, target detection and other research directions
随机推荐
Export excel, generate multiple sheet pages, and name them
How about ink cloud?
Printf function of input and output function in C language
JUC笔记
Advanced multi threading: the underlying principle of synchronized, the process of lock optimization and lock upgrade
Long和Integer如何进行比较,为什么报错
(黑马)MYSQL初级-高级笔记(博主懒狗)
冶金物理化学复习 ---- 气固反应动力学
Openjudge: judge whether the string is palindrome
openjudge:石头剪刀布
openjudge:矩阵乘法
ArrayList多线程安全解决办法
The difference between get and post
2022 summer practice (PowerDesigner tutorial learning record) (first week)
How Visio can quickly generate the same pattern and image matrix
多线程进阶:锁的策略
C language characters and strings
Openjudge: stone scissors cloth
论文写作用词
Personal summary of restful interface use

