Java happens-before relationship?

Tags: , , , ,



Consider the following code.

public class Test {
    private boolean running = false;

    public void run() {
        running = true;
    }

    public void test() {
        boolean running1 = running;
        boolean running2 = running;
        System.out.println("running1: " + running1);
        System.out.println("running2: " + running2);
    }
}

Thread A calls run(), then another thread B calls test() and there shouldn’t be any happens-before relationship. I know it is not guaranteed that thread B sees the changes which thread A made. But is it possible that the output of this program is:

running1: true
running2: false

Answer

Yes, it’s possible, because it’s not explicitly forbidden.

The read of running for the assignments to running1 and running2 can happen in any order with respect to each other, and the read for running2 could happen after the first System.out.println. And there’s nothing to say that either of the reads should be from cache or main memory.

Basically, it’s very open as to what that can print (and why).



Source: stackoverflow