JMM
What is JMM?
JMM: java memory model, non-existent things, concepts, conventions
Some synchronization conventions about JMM
1. Before the thread is unlocked, the shared variable must be immediately flushed back to the main memory
2. Before the thread is locked, it must read the latest worthy working memory in the main memory
3. Locking and unlocking are the same lock
Volatile is a lightweight synchronization mechanism provided by the java virtual machine
1. Ensure visibility
package com.xizi.volatie;
import java.util.concurrent.TimeUnit;
public class JMMdemo {
//不加 volatile 程序就会死循环
//volatile 可以保证可见性
private volatile static int num=0;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
while (num==0){
}
}).start();
TimeUnit.SECONDS.sleep(2);
num=1;
System.out.println(num);
}
}
2. No guarantee of atomicity
Atomicity: indivisible
Thread A cannot be interrupted and cannot be divided while performing tasks. Either succeed or fail at the same time
package com.xizi.volatie;
public class Volatiledemo2 {
// volatile 不保证原子性
private volatile static int num=0;
//synchronized 20000
public static void add(){
num++;
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 1000; i1++) {
add();
}
}).start();
}
while (Thread.activeCount()>2){
Thread.yield();
}
System.out.println( num);
}
}
How to ensure atomicity if Lock and synchronized are not used
Use atomic classes to solve atomicity problems
package com.xizi.volatie;
import java.util.concurrent.atomic.AtomicInteger;
public class Volatiledemo2 {
// volatile 不保证原子性
private volatile static AtomicInteger num=new AtomicInteger();
//synchronized 20000
public static void add(){
// num++;//
num.getAndIncrement();// 方法:CAS AtomicInteger +1
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 1000; i1++) {
add();
}
}).start();
}
while (Thread.activeCount()>2){
Thread.yield();
}
System.out.println( num);
}
}
These classes have to be hooked to the operating system at the bottom level to modify values in memory. The Unsafe class is a very special one.
3. Prohibition of order rearrangement
Source code --> Compiler optimized rearrangement --> Instruction parallel may also be rearranged --> Memory system will also be rearranged --> Execution
The processor considers the dependencies between data when reordering instructions
Valatile avoids command rearrangement:
Memory barrier, CUP instruction function
1. Ensure the order of execution of specific operations
2. The memory visibility of certain variables can be guaranteed