java reordering and memory model
Asked Answered
T

1

7

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?.

Toandfro answered 3/5, 2012 at 21:24 Comment(0)
A
13

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.

Armourer answered 3/5, 2012 at 21:27 Comment(3)
Based on what the JLS says : The JIT decides that a Happens before is not needed if there is no dependency between two events (if they are independent) right?. This paragraph is pointing to JIT optimizations correct?Skater
@TheLostMind: Well, either JIT optimizations or just the JIT not removing CPU optimizationsArmourer
In that case, eventually, a happens before doesn't exist. I smell the hand of escape analysis in this one :PSkater

© 2022 - 2024 — McMap. All rights reserved.