I am reading the JLS spec on memory model, 17.4.5 Happens-before Order.
I do not understand 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:
-
According to the above rule, does it mean hb(ActionA,ActionB)?
-
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?
-
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:
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)