【发布时间】:2019-04-19 16:09:11
【问题描述】:
想知道JVM在使用synchronized时如何保证被引用对象中成员变量修改的可见性。
我知道 synchronized 和 volatile 将为变量修改提供可见性。
class Test{
public int a=0;
public void modify(){
a+=1;
}
}
//Example:
// Thread A:
volatile Test test=new Test();
synchronized(locker){
test.modify();
}
// then thread B:
synchronized(locker){
test.modify();
}
// Now, I think test.a==2 is true. Is it ok? How JVM implements it?
// I know the memory barrier, does it flush all cache to main storage?
线程 A 调用首先在 sychronized 块中进行修改,然后将对象传递给线程 B(写入对 volatile 变量的引用。)。
然后线程 B 再次调用 modify(在synchronized)。
a==2 有什么保证吗? JVM是如何实现的?
【问题讨论】:
-
您的示例代码与您描述的场景不匹配,并且不完整,请更新您的问题,以便我们确定我们理解您的真正要求。
-
@StephenC 好的,我编辑这段代码。
-
是的,在 A 和 B 运行之后,a 将等于 2。而且这里不需要 volatile。
-
这仍然不是一个完整的例子。提示:如果我不能将它复制到文件中,编译并运行它,它是不完整的。在这种情况下,仍然缺少重要的细节。 (@NathanHughes 做了一些假设……)
-
@Stephen C 好的,我会尽快编辑它