Java memory model: volatile variables and happens-before -
i'd clarify how happens-before relation works volatile variables. let have 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 following statements correct in accordance java memory model (jmm)? if not, correct interpretation?
i = 1
happens-beforev = 2
v = 2
happens-beforevdst = v
in jmm if it's happens before in timei = 1
happens-beforeidst = i
in jmm (andidst
predictably assigned1
) ifv = 2
happens beforevdst = v
in time- otherwise order between
i = 1
,idst = i
undefined , resulting value ofidst
undefined well
mistake in logic:
there no "wall clock time" concept in jmm, , should rely on synchronization order ordering guide v = 2
, vdst = v
. see chosen answer further details.
i = 1
happens-beforev = 2
true. jls section 17.4.5,
if x , y actions of same thread , x comes before y in program order, hb(x, y).
v = 2
happens-beforevdst = v
in jmm if it's happens before in timei = 1
happens-beforeidst = i
in jmm (andidst
predictably assigned1
) ifv = 2
happens beforevdst = v
in time
false. happens-before order not make guarantees things happening before each other in physical time. same section of jls,
it should noted presence of happens-before relationship between 2 actions not imply have take place in order in implementation. if reordering produces results consistent legal execution, not illegal.
it is, however, guaranteed v = 2
happens-before vdst = v
, i = 1
happens-before idst = i
if v = 2
comes before vdst = v
in synchronization order, total order on synchronization actions of execution mistaken real-time order.
- otherwise order between
i = 1
,idst = i
undefined , resulting value ofidst
undefined well
this case if vdst = v
comes before v = 2
in synchronization order, actual time doesn't come it.
Comments
Post a Comment