当前位置:网站首页>Concurrent programming (XXIV) - JMM's happens before principle
Concurrent programming (XXIV) - JMM's happens before principle
2022-07-21 21:12:00 【Super_ Leng】
List of articles
One 、happens-before Introduce
1. describe
happens-before It specifies that the write operation to the shared variable is visible to the read operation of other threads , There must exist between these two operations happens-before Relationship , It's a summary of a set of rules for visibility and order , namely Antecedent principle .
- If an operation happens-before Another operation , Then the execution result of the first operation will be visible to the second operation ( visibility ), And the execution order of the first operation is before the second operation ( Orderliness )
- There is... Between the two operations happens-before Relationship , Doesn't mean you have to follow happens-before The order in which the principles are laid down . If the execution result after reordering is in accordance with happens-before Relationship Consistent result , So this reordering Not illegal ( You can order a rearrangement )
2. explain
- If Java The orderliness in the memory model depends only on volatile and synchronized To complete , Then many operations will become very cumbersome , But we're writing Java Concurrent code doesn't notice this , as a result of : stay JMM There is happens-before Principle limits .
- This principle is very important : It's about judging whether there's competition in the data , A useful means of thread safety . Rely on this principle , It can solve all the problems of whether there is conflict between two operations in the concurrent scenario , You don't have to fall into JMM Obscure underlying compilation principles .
3. Case study
Two 、happens-before The rules
If you put aside the following happens-before The rules ,JMM It doesn't guarantee that a thread can write shared variables , The reading of the shared variable by other threads is visible .
Be careful : The following variables refer to member variables or static member variables
1. Order rules
- In one thread , In code order , Written in Front operation Occurs first in Written in Later operations ( The result of the previous operation can be obtained by subsequent operations )
2. Locking rules
- Thread unlock Before Write variables , about Other Thread lock when Reading this variable so ( For the same lock , You must wait for the previous thread to unlock , Other threads can lock )
static Object m = new Object();
new Thread(()->{
synchronized(m) {
x = 10;
}
},"t1").start();
new Thread(()->{
synchronized(m) {
System.out.println(x);
}
},"t2").start();
3. volatile Variable rule
- Threads Yes volatile Variable writing , about Other thread pairs Reading of this variable so
volatile static int x;
new Thread(()->{
x = 10;
},"t1").start();
new Thread(()->{
System.out.println(x);
},"t2").start();
4. Transfer rules
- The visibility of variable values is transitive , If x happens-before y also y happens-before z So there are x happens-before z
volatile static int x;
static int y;
new Thread(()->{
y = 10;
x = 20;
},"t1").start();
new Thread(()->{
// x=20 Yes t2 so , meanwhile y=10 Also on the t2 so
System.out.println(x);
},"t2").start();
5. Thread start rule (Thread Start Rule)
- Threads start Before Write variables , about After the thread starts Reading this variable so
static int x; x = 10;
new Thread(()->{
// Only the thread start after , Can be obtained by output operation x Value
System.out.println(x);
},"t2").start();
6. Thread interrupt rule (Thread Interruption Rule)
- t1 Threads interrupt t2 Before thread Write variables , For other threads hear t2 After the thread is interrupted Reading variables so
static int x;
public static void main(String[] args) {
Thread t2 = new Thread(()->{
while(true) {
if(Thread.currentThread().isInterrupted()) {
System.out.println(x);
break;
}
}
},"t2");
t2.start();
new Thread(()->{
sleep(1);
x = 10;
t2.interrupt();
},"t1").start();
while(!t2.isInterrupted()) {
Thread.yield();
}
System.out.println(x);
}
7. Thread abort rule (Thread Termination Rule)
- Before the thread ends Write variables , about Other threads Read after knowing it is over so ( For example, other thread calls t1.isAlive() or t1.join() Wait for it to end )
static int x;
Thread t1 = new Thread(()->{
x = 10;
},"t1");
t1.start();
t1.join();
System.out.println(x);
8. Termination Rules for objects (Finalizer Rule)
- Initialization of an object completed ( End of constructor execution ), What happened first finalize() The beginning of the method
( Only objects are created first , There's a follow-up JVM Of GC,GC Will finally execute finalize() Method , So an object is created before finalize() Before method execution ) - Default values for variables (0,false,null) The writing of , For other threads to read the variable can be seen
3、 ... and 、 Case description
private int value=0;
public void setValue(){
this.value=value;
}
public int getValue(){
return value;
}
Solution :
- Lock read and write operations
- Use volatile, Lock only write operations
Four 、 summary
stay Java In language ,happens-before The Semantic Essence of is a kind of visibility
- A happens-before B, signify A What happened is right B It's visible , No matter what A and B Whether it happens in the same thread
JMM The design is divided into two parts :
- For programmers happens-before The rules , Easy to understand to explain a strong memory model to programmers , Only understand happens-before The rules , You can write concurrent and safe programs
- in the light of JVM The implementation of the , In order to minimize the constraints on the compiler and processor so as to improve the performance , JMM No requirements are made on the premise of not affecting the execution results of the program , Optimization allows reordering .
边栏推荐
猜你喜欢
(Sword finger offer version) string inversion
如何在执行前测试 Insert 和 Update 语句
Matlab2021a configuration GPU encountered error c1083: unable to open include file: "gpu/mxgpuarray.h": no such file or directory
易语言学习笔记(三)
Add whitelist function for NFT based on Merkle tree (translation)
Volcano engine & SouFun: wisdom and "recommendation" behind clothing wholesale
并发编程(二十九) - 对象的内存布局
并发编程(二十五) - volatile与final原理
C language 2022 Shanxi upgraded C language knowledge points
SQL 汇总数据
随机推荐
peoplecode 对象和类
「互动有礼,感谢有你」参与互动就有机会获赠 Navicat Premium 16
Oracle 使用数据操作函数
Vs+qt debug is changed to release version to export records
并发编程(二十四) - JMM之happens-before原则
[epidemic analysis -- data collection]
PCL runtime ucrtbased Exception thrown by DLL
Learn MySQL in one day --- learning notes (I)
Redis(三) - Redis常见命令
Navicat 16.1 为OceanBase 社区版提供管理开发工具的新选择
并发编程(三十) - ThreadLocal 原理与实践
Rust简短笔记:4种不同的引用变量解答
How to match multiple point clouds step by step
[permission promotion] MySQL authorization raising method
Rust简短笔记:原始指针(Raw Pointer)
投票 | 选出您希望Navicat支持的数据库
Easy language learning notes (III)
Solidity中的mapping为何不提供按照key遍历的功能?
Redis (vii) - encapsule la classe d'outils redis
Causes and patches of virtual machine ventilation of Win9x in new processors such as ryzen