![](/img/trans.png)
[英]Happens-before relationships with volatile fields and synchronized blocks in Java - and their impact on non-volatile variables?
[英]Volatile happens-before relationship when there's mix of volatile and non-volatile fields
当易失性和非易失性字段混合时,我试图了解易失性字段的发生前行为。
假设有 1 个 WriteThread 和 5 个 ReadThreads,它们更新/读取 SharedObject。
ReadThreads 从一开始就调用方法waitToBeStopped()
,WriteThread 在 1 秒后调用方法stop()
。
public class SharedObject {
volatile boolean stopRequested = false;
int a = 0, b = 0, c = 0;
int d = 0, e = 0, f = 0;
// WriteThread calls this method
public void stop() {
a = 1;
b = 2;
c = 3;
stopRequested = true;
a = 4;
b = 5;
c = 6;
d = 7;
e = 8;
f = 9;
}
// ReadThread calls this method
public void waitToBeStopped() throws Exception {
while(!stopRequested) {
}
System.out.println("Stopped now.");
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + f);
}
}
当这个程序结束时,output 是这样的。 即使我尝试了 100 多个 ReadThreads,结果也总是一样的。
Stopped now.
Stopped now.
Stopped now.
Stopped now.
Stopped now.
4 5 6 7 8 9
4 5 6 7 8 9
4 5 6 7 8 9
4 5 6 7 8 9
4 5 6 7 8 9
Q1。 有人可以解释为什么这总是返回 4,5,6,7,8,9 而不是 1,2,3,0,0,0?
我对happens-before关系的理解是这样的:
a=1,b=2,c=3
发生在WriteThread 写入stopRequested
之前stopRequested
发生在WriteThread 写入a=4,b=5,c=6,d=7,e=8,f=9
之前stopRequested
发生在ReadThread 读取stopRequested
之前stopRequested
发生在ReadThread 读取a,b,c,d,e,f
之前从这 4 个陈述中,我无法得出这样的陈述……
a=4,b=5,c=6,d=7,e=8,f=9
发生在ReadThread 读取a,b,c,d,e,f
之前如果有帮助,这是代码的另一部分:
public class App {
public static void main(String[] args) throws Exception {
SharedObject sharedObject = new SharedObject();
for(int i =0 ; i < 5; i++) {
Runnable rThread = new ReadThread(sharedObject);
new Thread(rThread).start();
}
Runnable wThread = new WriteThread(sharedObject);
new Thread(wThread).start();
}
}
public class WriteThread implements Runnable {
private SharedObject sharedObject;
public WriteThread(SharedObject sharedObject) {
this.sharedObject = sharedObject;
}
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
sharedObject.stop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class ReadThread implements Runnable {
private SharedObject sharedObject;
public ReadThread(SharedObject sharedObject) {
this.sharedObject = sharedObject;
}
public void run() {
try {
sharedObject.waitToBeStopped();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
您假设stopRequested = true;
不保证对读者可见是正确的。 编写者没有保证将这些写入写入共享缓存/内存,在这些缓存/内存中它们对读者可见。 它可以将它们写入本地缓存,而读者不会看到更新的值。
Java语言保证了可见性,例如当您使用 volatile 变量时。 但它不保证非易失性变量上的更改对其他线程不可见。 在您的情况下,此类写入仍然可以看到。 处理器的 JVM 实现、memory 一致性 model 和其他方面影响可见性。
请注意,JLS 和happens-before 关系是一个规范。 JVM 实现和硬件通常比 JLS 指定的更多,这可能导致 JLS 不需要可见的写入可见性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.