As I know, JMM does not follow Sequential Consistency, and we need the volatile keyword to guarantee visibility. A typical example without SC often describe like
A = 0;
B = 0;
--thread 1--
A = 1;
B = 1;
--thread 2--
if(B == 1){
//at here, A is not guarantee equal to 1, A == 0 is also possible
}
Which is easy to understand. But when I want to reproduce this simple example in real Java code, I failed.
Below is the code I hope to reproduce the above concept example, I do not use the volatile here, but this code still never reach the case when a==0 and b==1.
import java.util.LinkedList;
public class test2 {
static int a = 0;
static int b = 0;
static class Multithreading1 extends Thread {
public void run() {
try {
sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
a = 1;
b = 1;
}
}
static class Multithreading2 extends Thread {
public void run() {
while (b == 0) {
Thread.onSpinWait();
}
if (a == 0) {
//never reach
System.out.print(a);
}
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
a = 0;
b = 0;
Multithreading1 t1 = new Multithreading1();
t1.start();
LinkedList<Multithreading2> t2 = new LinkedList();
int thread_number = 16;
for (int j = 0; j < thread_number; j++) {
t2.add(new Multithreading2());
}
for (int j = 0; j < thread_number; j++) {
t2.get(j).start();
}
for (int j = 0; j < thread_number; j++) {
t2.get(j).join();
}
t1.join();
}
}
}
Am I doing anything wrong? Or is there any hidden mechanism behind my fail, if so, is it possible to build a real code example that shows Java does not follow the sequential consistency?
By the way, my java version is OpenJDK Runtime Environment Corretto-11.0.8.10.1