Temple Wing
Temple Wing

Reputation: 429

java concurrency in practice 16.1

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?

Upvotes: 3

Views: 141

Answers (1)

Keppil
Keppil

Reputation: 46239

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-before in the Javaspecs here:

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.

For example, if the first run() method looked like this:

public void run() {
    b = 1;
    x = b;
}

no reordering would be permitted.

Upvotes: 3

Related Questions