I am currently studying for a concurrent programming exam and don't understand why the output of this program is 43. Why is x = y + 1 executed before t.start()? I also should explain which happens-before rules I used.
If I understand the program order rule (each action in a thread happens-before every action in that thread that comes later in the program order) t.start() has to be executed before x = y + 1 so that thread t copies variable x which will be 1.
public class HappensBefore {
static int x = 0;
static int y = 42;
public static void main(String[] args) {
    x = 1;
    Thread t = new Thread() {
        public void run() {
            y = x;
            System.out.println(y);
        };
    };
    t.start();
    x = y + 1;
}
                There is no synchronization, no volatile fields, no locking, no atomic fields. The code can execute in any order.
Yes, t.start() will execute before x = y + 1. But starting the thread doesn't mean the thread body executes before x = y + 1. It could run before, or after, or interleaved with the rest of main().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With