Java – Object visibility across threads

concurrencyjava

I have a general doubt regarding publishing data and data changes across threads.
Consider for example the following class.

public class DataRace {
  static int a = 0;

  public static void main() {
    new MyThread().start();
    a = 1;
  }

  public static class MyThread extends Thread {
    public void run() { 
      // Access a, b.
    }
  }
}

Lets focus on main().

Clearly

new MyThread().start();
a = 1;

There we change the shared variable a after the MyThread is started and thus may not be a thread-safe publication.

a = 1;
new MyThread().start();

However this time the change in a is safely published across the new thread, since Java Language Specification (JLS) guarantees that all variables that were visible to a thread A when it starts a thread B are visible to thread B, which is effectively like having an implicit synchronization in Thread.start().

new MyThread().start();
int b = 1;

In this case when a new variable is allocated after both the threads have been spawned, is there any guarantee that that the new variable will be safely published to all threads. i.e. if var b is accessed by the other thread, is it guaranteed to see its value as 1. Note that I'm not talking about any subsequent modifications to b after this (which certainly needs to be synchronized), but the first allocation done by the jvm.

Thanks,

Best Solution

I wasn't not entirely sure about this one:

a = 1;
new MyThread().start();

... in that I wasn't sure there was any guarantee that the value of a would be "flushed" to shared memory before the new thread started. However, the spec explicitly talks about this. In section 17.4.4 it states:

An action that starts a thread synchronizes-with the first action in the thread it starts.

(The discussion after that basically shows that it'll be okay.)

I'm not sure what your last example (with b) is meant to be about.