I found this to give interesting results depending on the processor's architecure x86 vs 64bits.
public class WhileTrueTest
{
boolean keepGoing = true;
volatile boolean volatileKeepGoing = true;
public static void main( String[] args ) throws InterruptedException
{
new WhileTrueTest().go();
}
private void go() throws InterruptedException
{
final Thread tNormal = new InnerNormal();
final Thread tVolatile = new InnerVolatile();
tNormal.start();
tVolatile.start();
Thread.sleep( 1000 );
keepGoing = false;
volatileKeepGoing = false;
Thread.sleep( 1000 );
System.out.printf("Threads shouldn't be alive. Are they? Normal:%s Volatile:%s",
tNormal.isAlive(),
tVolatile.isAlive());
System.out.println();
System.exit(1);
}
class InnerNormal extends Thread
{
@Override
public void run()
{
while(keepGoing) {}
}
}
class InnerVolatile extends Thread
{
@Override
public void run()
{
while(volatileKeepGoing) {}
}
}
}