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;
and thread A:
i = 1;
v = 2;
and thread B:
vDst = v;
iDst = i;
Are the following statements correct in accordance with Java memory model (JMM)? If not, what would be correct interpretation?
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
Mistake in the logic:
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.