Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Happens-before rules in Java Memory Model

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;
}
like image 235
lmaonuts Avatar asked Jan 27 '18 14:01

lmaonuts


1 Answers

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

like image 94
John Kugelman Avatar answered Sep 29 '22 23:09

John Kugelman