Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

Java memory model: volatile variables and happens-before

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-before v = 2
  • v = 2 happens-before vDst = v in JMM only if it's actually happens before in time
  • i = 1 happens-before iDst = i in JMM (and iDst will be predictably assigned 1) if v = 2 actually happens before vDst = v in time
  • Otherwise order between i = 1 and iDst = i is undefined and resulting value of iDst 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • i = 1 always happens-before v = 2

True. By JLS section 17.4.5,

If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).


  • v = 2 happens-before vDst = v in JMM only if it's actually happens before in time
  • i = 1 happens-before iDst = i in JMM (and iDst will be predictably assigned 1) if v = 2 actually happens before vDst = v in time

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,

It should be noted that the presence of a happens-before relationship between two actions does not necessarily imply that they have to take place in that order in an implementation. If the reordering produces results consistent with a legal execution, it is not illegal.

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.


  • Otherwise order between i = 1 and iDst = i is undefined and resulting value of iDst is undefined as well

This is the case if vDst = v comes before v = 2 in the synchronization order, but actual time doesn't come into it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...