Instruction reordering & happens-before relationship [duplicate]

The key point of the program order rule is: in a thread.

Imagine this simple program (all variables initially 0):

T1:

x = 5;
y = 6;

T2:

if (y == 6) System.out.println(x);

From T1’s perspective, an execution must be consistent with y being assigned after x (program order). However from T2’s perspective this does not have to be the case and T2 might print 0.

T1 is actually allowed to assign y first as the 2 assignements are independent and swapping them does not affect T1’s execution.

With proper synchronization, T2 will always print 5 or nothing.

EDIT

You seem to be misinterpreting the meaning of program order. The program order rule boils down to:

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

happens-before has a very specific meaning in the JMM. In particular, it does not mean that y=6 must be subsequent to x=5 in T1 from a wall clock perspective. It only means that the sequence of actions executed by T1 must be consistent with that order. You can also refer to JLS 17.4.5:

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.

In the example I gave above, you will agree that from T1’s perspective (i.e. in a single threaded program), x=5;y=6; is consistent with y=6;x=5; since you don’t read the values. A statement on the next line is guaranteed, in T1, to see those 2 actions, regardless of the order in which they were performed.

Leave a Comment