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;
}
}
}