Hi,
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,