Are operations before Thread.start() thread safe in relation to the new thread?

39 Views Asked by At

Are there any guarantees to the variable visibility and/or ordering of instructions before Thread.start() in relation to the starting of the new thread?

Specifically, in the minimalistic example below, am I correct in assuming that var should be volatile in order for the output to be deterministic and always print "var = 10"?

public class ThreadExample {

    private int var;

    void example() {
        var = 10;
        Thread thread = new MyThread();
        thread.start();
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("var = " + var);
        }
    }

}

Note: My question only applies to the "new" Java memory model introduced in Java 5

0

There are 0 best solutions below