1

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
stonar96
  • 1,359
  • 2
  • 11
  • 39
  • This is almost my question, but not exectly. In the suggested answer two different variables are used. However I only read from one variable. So the answer is: This doesn't answer my question completely. **Edit:** https://stackoverflow.com/q/16213443/3882565 was suggested. – stonar96 Jun 22 '20 at 20:42
  • 1
    "But is it possible that [...]": yes, it is (whatever "[...]" is). The behavior of the program is undefined, so literally anything can happen. – Bruno Reis Jun 22 '20 at 23:29

1 Answers1

5

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

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Thanks, this answer helped a lot, but now I have another question. What if i replace it by `boolean running1 = running; boolean running2; if (running1) { running2 = running; }`. Now it seems like it can't be reordered, or can it? It would be nice if you can also cover this case in your answer. – stonar96 Jun 22 '20 at 21:09