There is such a saying in this question:
All caches are coherent. That is, you will never had two different values for the same memory location. This coherency is maintained by a version of the MESI protocol
My question is why iv.stop
is always false
in the block of code below, it seems that cache coherency doesn't take effect. BTW, my PC's CPU is i7-4700HQ.
I definitely know right here there is no happens-before relationship between the read action and the write action of the shared variable stop
and this is a data race in Java. I just want to know why cache coherency doesn't take effect. Because thread t2 has changed the cache of stop
in its running core, it seems that the core's cache should see this change where thread t1 is running according to cache coherency.
public class InfiniteLoop {
boolean stop = false;
Boolean another = null;
public static void main(String[] args) {
final InfiniteLoop iv = new InfiniteLoop();
Thread t1 = new Thread(() -> {
System.out.println("t1 iv address-->"+iv); //t1 iv address-->com.nestvision.thread.InfiniteLoop@48b96cb8
while (!iv.stop) {
//Not System.out.println(iv.stop) here to avoid
//a lock action of PrintStream object.
iv.another = iv.stop;
}
System.out.println("done");
});
Thread t2 = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 iv address-->"+iv);//t2 iv address-->com.nestvision.thread.InfiniteLoop@48b96cb8
iv.stop = true;
System.out.println("t2 end");
});
t2.start();
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(iv.another); //this will print 'false'
}
}
iv
in each thread you'd see in the code above, they're the same object as prediction. – XiangZzz