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-before v = 2
  • v = 2 happens-before vdst = v in jmm if it's happens before in time
  • i = 1 happens-before idst = i in jmm (and idst predictably assigned 1) if v = 2 happens before vdst = v in time
  • otherwise order between i = 1 , idst = i undefined , resulting value of idst 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-before v = 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-before vdst = v in jmm if it's happens before in time
  • i = 1 happens-before idst = i in jmm (and idst predictably assigned 1) if v = 2 happens before vdst = 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 of idst undefined well

this case if vdst = v comes before v = 2 in synchronization order, actual time doesn't come it.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -