0

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

LoPoBo
  • 1,767
  • 1
  • 15
  • 26
  • 1
    JLS [§17.4.4. Synchronization Order](https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.4): "An action that starts a thread *synchronizes-with* the first action in the thread it starts." – Andreas May 30 '17 at 10:37
  • 1
    More specifically: JLS [§17.4.5. Happens-before Order](https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5): "A call to `start()` on a thread *happens-before* any actions in the started thread." So no, you do not need to make it `volatile`. – Andreas May 30 '17 at 10:40

0 Answers0