问题描述
我想说明 happens-before 关系如何与 volatile 变量一起使用.让我们有以下变量:
I'd like to clarify how happens-before relation works with volatile variables. Let we have the following variables:
public static int i, iDst, vDst;
public static volatile int v;
和线程A:
i = 1;
v = 2;
和线程B:
vDst = v;
iDst = i;
以下语句是否符合Java内存模型(JMM)??如果不正确,什么是正确的解释?
Are the following statements correct in accordance with Java memory model (JMM)? If not, what would be correct interpretation?
-
i = 1
总是在发生之前v = 2
仅在JMM中 -
v = 2
在...之前发生vDst = v
如果v = 2
实际上在时间上早于vDst = v
之前,则JMM中的 -
i = 1
发生在iDst = i
(并且iDst
将可预测地分配为1
) - 否则
i = 1
和iDst = i
之间的顺序不确定,并且iDst
的结果值也不确定
i = 1
always happens-beforev = 2
v = 2
happens-beforevDst = v
in JMM only if it's actually happens before in timei = 1
happens-beforeiDst = i
in JMM (andiDst
will be predictably assigned1
) ifv = 2
actually happens beforevDst = v
in time- Otherwise order between
i = 1
andiDst = i
is undefined and resulting value ofiDst
is undefined as well
逻辑错误:
JMM中没有挂钟时间"的概念,我们应该依靠同步顺序作为v = 2
和vDst = v
的排序指南.有关更多详细信息,请参见所选答案.
There is no "wall clock time" concept in JMM, and we should rely on synchronization order as an ordering guide for v = 2
and vDst = v
. See the chosen answer for further details.
推荐答案
-
i = 1
总是在发生之前v = 2
i = 1
always happens-beforev = 2
-
v = 2
在...之前发生vDst = v
如果v = 2
实际上在时间上早于vDst = v
之前,则JMM中的 -
i = 1
发生在iDst = i
(并且iDst
将可预测地分配为1
) v = 2
happens-beforevDst = v
in JMM only if it's actually happens before in timei = 1
happens-beforeiDst = i
in JMM (andiDst
will be predictably assigned1
) ifv = 2
actually happens beforevDst = v
in time- 否则
i = 1
和iDst = i
之间的顺序不确定,并且iDst
的结果值也不确定 - Otherwise order between
i = 1
andiDst = i
is undefined and resulting value ofiDst
is undefined as well
是的.通过JLS部分 17.4.5 ,
True. By JLS section 17.4.5,
- 仅在JMM中
错.先发生先后顺序并不能保证事情在物理上先于先发生.在JLS的同一部分,
False. The happens-before order does not make guarantees about things happening before each other in physical time. From the same section of the JLS,
但是,如果v = 2
出现在v = 2
vDst = v
和i = 1
happens-before iDst = i
之前,则可以保证v = 2
c3>按照同步顺序,通常是误认为实时顺序的执行同步动作的总顺序.
It is, however, guaranteed that v = 2
happens-before vDst = v
and i = 1
happens-before iDst = i
if v = 2
comes before vDst = v
in the synchronization order, a total order over the synchronization actions of an execution that is often mistaken for the real-time order.
如果vDst = v
按照同步顺序排在v = 2
之前,则是这种情况,但实际时间没有计算在内.
This is the case if vDst = v
comes before v = 2
in the synchronization order, but actual time doesn't come into it.
这篇关于Java内存模型:易变变量和发生之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!