In this code:
public class PossibleReordering {
static int x = 0, y = 0;
static int a = 0, b = 0;
public static void main(String[] args)
throws InterruptedException {
Thread one = new Thread(new Runnable() {
public void run() {
a = 1;
x = b;
}
});
Thread other = new Thread(new Runnable() {
public void run() {
b = 1;
y = a;
}
});
one.start(); other.start();
one.join(); other.join();
System.out.println("( "+ x + "," + y + ")");
}
}
They say Java Compiler will reorder the instructions in thread one and thread other to optimize its execution, and finally cause the result (0,0).
And also they say:
Each action in a thread happens-before every action in that thread that comes later in the program order.
Does those two statement conflict with each other?
The happens-before rule only applies to statements that depend on each other. Since these
run()methods both contain assignments that are independent, the compiler is allowed to reorder them, which may cause the output you describe.You can read the definition of
happens-beforein the Javaspecs here:For example, if the first
run()method looked like this:no reordering would be permitted.