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 = 1happens-beforev = 2v = 2happens-beforevdst = vin jmm if it's happens before in timei = 1happens-beforeidst = iin jmm (andidstpredictably assigned1) ifv = 2happens beforevdst = vin time- otherwise order between
i = 1,idst = iundefined , resulting value ofidstundefined 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 = 1happens-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 = 2happens-beforevdst = vin jmm if it's happens before in timei = 1happens-beforeidst = iin jmm (andidstpredictably assigned1) ifv = 2happens beforevdst = vin 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 = iundefined , resulting value ofidstundefined well
this case if vdst = v comes before v = 2 in synchronization order, actual time doesn't come it.
Comments
Post a Comment