The other day someone asked me to demonstrate how volatile variables work in Java. Heres an example. Consider a few threads that periodically check a shared flag. If the flag is set to true (by another thread), the threads stop running. I'll use BusyTask to simulate a long running process. BusyTask checks a shared flag -- a member variable in ShutdownDriver. ShutdownDriver starts BusyTasks and sets the shared flag to true after sleeping for a few seconds. If the shared flag is not volatile, the BusyTask keep running forever. This makes the case for volatile.
/**
 * @(#) ShutdownMonitor.java Apr 8, 2008 5:20:06 PM
 */
package sync.vol;

/**
 * Represents a busy process that should shutdown when
 * ShutdownDriver.shutdown is set to true.
 */
public class BusyTask extends Thread {
	private ShutdownDriver driver;

	public BusyTask(ShutdownDriver driver) {
		this.driver = driver;
	}

	/**
	 * If another thread sets ShutdownDriver.shutdown to
	 * true this thread should terminate.
	 */
	public void run() {
		while (!driver.shutdown) {
		}
		System.out.println("Busy task stopped!");
	}
}
/**
 * @(#) ShutdownDriver.java Apr 8, 2008 5:23:15 PM
 */
package sync.vol;

/**
 * Flags for shutdown by setting shutdown to true.
 */
public class ShutdownDriver {
	/**
	 * This should be a volatile field!
	 */
	boolean shutdown = false;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ShutdownDriver driver = new ShutdownDriver();
		BusyTask task = new BusyTask(driver);
		task.start();

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		driver.shutdown = true;
	}
}
When ShutdownDriver.shutdown is not volatile, without the -server option, I never saw Busy task stopped! printed out.

NOTE: When you use -server option, the VM optimizes your program for maximum speed. So it is highly likely that with this option, BusyTask never terminates. My guess is with -server option, compiler optimizes aggressivley resulting in the variable shutdown being hoisted above the loop.

Resources

  1. http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html
  2. http://www.ibm.com/developerworks/java/library/j-jtp06197.html
  3. http://www.javaperformancetuning.com/tips/volatile.shtml