Does volatile write assure that whatever writes (non-volatile / volatile writes) happens before it in one thread will be visible to other thread?
Will the following given code always produce 90,80
as output?
public class MyClass
{
private boolean flag = false;
private volatile int volatileInt = 0;
private int nonVolatileInt = 0;
public void initVariables()
{
nonVolatileInt = 90; // non-volatile write
volatileInt = 80; // volatile write
flag = true; // non-volatile write
}
public void readVariables()
{
while (flag == false)
{}
System.out.println(nonVolatileInt + ","+ volatileInt);
}
public static void main(String st[])
{
final MyClass myClass = new MyClass();
Thread writer = new Thread( new Runnable()
{
public void run()
{
myClass.initVariables();
}
});
Thread reader = new Thread ( new Runnable()
{
public void run()
{
myClass.readVariables();
}
});
reader.start();writer.start();
}
}
My concern is the method initVariables(). Isn't JVM has a freedom to reorder the code blocks in following way?:
flag = true;
nonVolatileInt = 90 ;
volatileInt = 80;
And consequently, we get the output by the reader thread as : 0,0
Or, they can be reordered in the following way:
nonVolatieInt = 90;
flag = true;
volatileInt = 80;
And consequently, we get the output by the reader thread as : 90,0