当前位置:网站首页>Volatile keyword and its function
Volatile keyword and its function
2022-07-27 03:23:00 【tea-Sir】
This paper mainly introduces Java In language volatile keyword , Content covered volatile Guaranteed memory visibility 、 Prohibit instruction rearrangement, etc .
1 Ensure memory visibility
1.1 Basic concepts
Visibility refers to the visibility between threads , The modified state of one thread is visible to another . This is the result of a thread modification , The other thread will see .
1.2 Realization principle
When right and wrong volatile When variables are read and written , Each thread copies variables from main memory to CPU In cache , If you have multiple computers CPU, Each thread may be in a different CPU Be dealt with on , This means that each thread can copy to a different CPU cache in .
volatile Variables are not cached in registers or invisible to other processors , It ensures that variables are read from main memory every time they are read or written , skip CPU cache This step . When a thread changes the value of this variable , The new value is immediately known to other threads .
2 Prohibit command rearrangement
2.1 Basic concepts
The order reorder is JVM To optimize instructions 、 Improve the efficiency of program operation , Without affecting the execution result of single thread program , Improve parallelism as much as possible . Instruction reordering includes compiler reordering and runtime reordering .
latile Variable prohibits reordering of instructions . in the light of volatile Decorated variable , A memory barrier is inserted before and after the read-write instruction , When reordering instructions, you cannot reorder subsequent instructions to the memory screen
example :
double r = 2.1; //(1)
double pi = 3.14;//(2)
double area = pi*r*r;//(3)
Although the definition order of code statements is 1->2->3, But the order of calculation 1->2->3 And 2->1->3 It has no effect on the results , So the compile time and run-time can adjust the 1、2 Reorder statements .
2.2 The problem of instruction rearrangement
If an operation is not atomic , Will give you JVM Leave a chance for rearrangement .
Threads A in
{
context = loadContext();
inited = true;
}
Threads B in
{
if (inited)
fun(context);
}
If the thread A The instructions in are reordered , that B It is very likely that you will get one that has not been initialized or has not been initialized yet context, This causes a program error .
2.3 The principle of prohibiting instruction rearrangement
volatile Keyword provides a memory barrier to prevent instructions from being rearranged , When the compiler generates bytecode files , A memory barrier is inserted in the instruction sequence to prevent a particular type of processor reordering .
JVM Memory barrier insertion strategy :
Every volatile Insert a... In front of the write operation StoreStore barrier ;
At every volatile Insert a... After the write operation StoreLoad barrier ;
At every volatile Insert a... After the read operation LoadLoad barrier ;
At every volatile Insert a... After the read operation LoadStore barrier .
2.4 The effect of instruction rearrangement in double locking singleton mode
Single case mode based on double test ( Lazy type )
public class Singleton3 {
private static Singleton3 instance = null;
private Singleton3() {}
public static Singleton3 getInstance() {
if (instance == null) {
synchronized(Singleton3.class) {
if (instance == null)
instance = new Singleton3();// Non atomic operation
}
}
return instance;
}
}
instance= new Singleton() It's not an atomic operation , It can actually be abstracted as the following JVM Instructions :
memory =allocate(); //1: Allocate memory space for objects
ctorInstance(memory); //2: Initialize object
instance =memory; //3: Set up instance Points to the memory address just allocated
Operation above 2 Dependent on operation 1, But operation 3 It doesn't depend on the operation 2. therefore JVM It is possible to optimize and reorder instructions for them , After reordering, it is as follows :
memory =allocate(); //1: Allocate memory space for objects
instance =memory; //3:instance Points to the memory address just allocated , The object is not initialized at this time
ctorInstance(memory); //2: Initialize object
After instruction rearrangement ,instance Pointing to the allocated memory is put in the front , The initialization of this memory is listed later . In a thread A Execute this assignment statement , The assignment object has been assigned to... Before initializing it instance quote , Just another thread enters the method judgment instance The reference is not null, Then return it to use , Make a mistake .
terms of settlement
use volatile Keyword modification instance Variable , bring instance reading 、 The memory barrier is inserted before and after the write operation , Avoid reordering .
public class Singleton3 {
private static volatile Singleton3 instance = null;
private Singleton3() {}
public static Singleton3 getInstance() {
if (instance == null) {
synchronized(Singleton3.class) {
if (instance == null)
instance = new Singleton3();
}
}
return instance;
}
}
3 volatile There is no guarantee of atomicity
because num++ Non atomic operation , First get num Value , Then write back the new num, Last new value num++;
A Threads and B The thread may take the same value at the same time , Causing thread insecurity .
resolvent : Add a... To the method synchronized keyword , But add synchronized There is no need to volatile 了 .
/** * @description:volatile Non atomic test * @author: teasir * @create: 2022/07/22 **/
public class VolatileVisibility {
private volatile int num;
public int inscrease(){
return num++;
}
}
4 Applicable scenario
(1)volatile Is a lightweight synchronization mechanism . During a visit to volatile The lock operation is not performed on a variable , So the thread will not block execution , It's a ratio. synchronized Keyword more lightweight synchronization mechanism .
(2)volatile Memory visibility and atomicity cannot be guaranteed at the same time . Locking mechanism ensures both visibility and atomicity , and volatile Variables only ensure visibility .
(3)volatile Cannot modify a variable whose write operation depends on the current value . Declare as volatile If the current value is related to the previous value of the variable , that volatile Keywords don't work , That is to say, the following expressions are not atomic operations :“count++”、“count = count+1”.
(4) When the variable to be accessed is already in synchronized Block of code , Or constant , There is no need to use volatile;
(5)volatile The shield is off JVM The necessary code optimizations in , So the efficiency is relatively low , So be sure to use this keyword when necessary .
边栏推荐
猜你喜欢

The diagram of user login verification process is well written!

win10/win11无损扩大C盘空间,跨盘合并C、E盘

Source code analysis of warning notification for skywalking series learning

延时队列的几种实现姿势?日常必备技能!
![[1206. Design skip table]](/img/a9/ca45c9fedd6e48387821bdc7ec625c.png)
[1206. Design skip table]

Details of impala implementation plan

注解@Autowired和@Resource的区别总结
![[learn FPGA programming from scratch -54]: high level chapter - FPGA development based on IP core - principle and configuration of PLL PLL IP core (Altera)](/img/4f/f75cfeb4422120ef9ac70cdeb0a840.png)
[learn FPGA programming from scratch -54]: high level chapter - FPGA development based on IP core - principle and configuration of PLL PLL IP core (Altera)

Pytoch loss function summary

太强了,一个注解搞定接口返回数据脱敏
随机推荐
Yilingsi T35 FPGA drives LVDS display screen
[flask] the server obtains the request header information of the client
关于OpenFeign的源码分析
win10/win11无损扩大C盘空间,跨盘合并C、E盘
索引最佳实践
Acwing 2074. Countdown simulation
How to uniquely identify a user SQL in Youxuan database cluster
最低票价(DAY 80)
Learn the recycling mechanism of recyclerview again
围圈报数(北理工机试题)(DAY 83)
深度学习——词汇embedded、Beam Search
二叉树(DAY 82)
[机缘参悟-52]:交浅言深要因人而异
Worthington木瓜蛋白酶解离系统解决方案
An error in the fourth edition of the red book?
力扣(LeetCode)207. 课程表(2022.07.26)
The diagram of user login verification process is well written!
PIP3 setting alicloud
[learn FPGA programming from scratch -54]: high level chapter - FPGA development based on IP core - principle and configuration of PLL PLL IP core (Altera)
Data Lake (20): Flink is compatible with iceberg, which is currently insufficient, and iceberg is compared with Hudi