开发者

Understanding JVM Happens-before and reorder

I am reading the JLS spec on memory model, 17.4.5 Happens-before Order. I do not understan开发者_如何学运维d the first rule:

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

Let's assume A an B are objects (instances of class object) that can be shared between multiple threads:

int i=A.getNum();  // ActionA
int j=B.getNum();  // ActionB

Three questions:

  1. According to the above rule, does it mean hb(ActionA,ActionB)?

  2. If the answer to 1 is true, does it mean according to happens-before rule, ActionB can not reordered to come before ActionA in any JVM that follows JSR133 memory model?

  3. If 1 and 2 both are true, it seems that ActionA and ActionB are not relevant, why can not reorder them? just for this spec?


It is my understanding that:

  1. you're right
  2. they can be reordered, but only if action B doesn't depend on result of action A

Happens-before relationship doesn't say anything about reordering actions. It only says that if HB(A, B) holds, then action B must see memory effects of action A.

If action B doesn't use any result of action A, then there is no reason why they cannot be reordered. (In general, "use any result of another action" is pretty broad, and it can only be detected for quite simple actions, like memory reads/writes, not for actions using external resources like I/O operations, or time-based operations)


Yes, ActionA happens before ActionB. Read further in that section though. It doesn't necessarily mean that the JVM can't reorder these. It means that ActionB must observe the effect of ActionA, that is all. If ActionB never depends on ActionA's effect, that is trivially true.


You are basically correct in your understanding. However, the key thing to remember is:

  • Reordering is allowed if it doesn't affect the outcome of the thread in which it runs
  • This doesn't mean reordering isn't allowed if it affects other threads

It is this last fact that is a common source of errors and bewilderment in multi-threaded programming in java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜