vjk
vjk

Reputation: 2283

java reordering and memory model

I am seeing this in the java specs:

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

and also this

original code
Thread 1
r2 = A;
B = 1;

valid compiler transformation(compilers are allowed to reorder the instructions in either thread, when this does not affect the execution of that thread in isolation)
Thread 1
B = 1;
r2 = A;

I am confused with those two things.
if an action x comes before an action y then x should happen before y. if we consider r2=A for x and B=1 for y, r2=A should happen before B=1. How can there be any reordering, how come B=1 is executed before r2=A if x happens before y is true?.

Upvotes: 7

Views: 594

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500475

Section 17.4.5 of the JLS specifically brings this out:

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.

If it helps, replace "happens-before" with "wurfles" everywhere in the spec, so that your intuition about what it means doesn't come into play. You're expecting guarantees which aren't present in the spec - due to the naming, I suspect.

Upvotes: 13

Related Questions