当前位置:网站首页>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 .
边栏推荐
猜你喜欢
随机推荐
Hcip day 14 notes
Portraiture5全新升级版磨皮滤镜插件神器
【1206. 设计跳表】
数据库红的表如何设计才能使性能更加优化
周全的照护 解析LYRIQ锐歌电池安全设计
Bulk copy baby upload prompt garbled, how to solve?
数据库使用安全策略
记录一次,php程序访问系统文件访问错误的问题
177. The nth highest salary (simple)
带你了解什么是 Web3.0
Functions that should be selected for URL encoding and decoding
排列与二进制(吉,大)(DAY 84)
国内服务器与海外服务器用1个数据库,怎样可以访问的快?
shell awk
Technology vane | interpretation of cloud native technology architecture maturity model
[flask] the server obtains the request header information of the client
volatile关键字及其作用
常见弱口令大全
PIP3 setting alicloud
window对象的常见事件


![[1206. Design skip table]](/img/a9/ca45c9fedd6e48387821bdc7ec625c.png)






