I need some help here. I am trying to create an example that shows volatile is needed to protect against instruction re-ordering.
In this example I am trying to show that b > a only if reordering happens and that volatile will prevent it.
The problem is that in every run I get b>a, and I must be missing something idiotic, but I can't see it.
What am I missing here?
public class Example04Reorder extends Thread {
volatile static int a = 0;
volatile static int b = 0;
public static void main(String[] args) throws InterruptedException {
Example04Reorder t = new Example04Reorder();
t.start();
while( true )
{
if ( b > a ) // supposedly happens only on reordering
{
System.out.println("b was bigger than a");
System.exit(1);
}
}
}
public void run() {
while (true)
{
a = 5;
b = 4;
b = 0;
a = 0;
}
}
}
There is no issue here. You have two read operations in your comparison operator. And since there is no delay between assignments in second thread they are executed momentarily. So it is possible that first thread got value 4 for b and when in read value for a it was already set to 0. So that is why you get your results.