Tuesday, April 5, 2011

Java volatile

volatile keyword is used to indicate that a variable's value will be modified by different threads.

Declaring a volatile Java variable means:
  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
  • Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

We say "acts as though" in the second point, because to the programmer at least (and probably in most JVM implementations) there is no actual lock object involved. Here is how synchronized and volatile compare:

Difference between synchronized and volatile

Characteristic Synchronized Volatile
Type of variable Object Object or primitive
Null allowed? No Yes
Can block? Yes No
All cached variables synchronized on access? Yes From Java 5 onwards
When synchronization happens When you explicitly enter/exit a synchronized block Whenever a volatile variable is accessed.
Can be used to combined several operations into an atomic operation Yes Pre-Java 5, no. Atomic get-set of volatiles possible in Java 5.



An example:
public class StoppableTask extends Thread {
  private volatile boolean stopThread;

  public void run() {
    while( !stopThread ) {
      // do something
    }
  }

  public void stopMe() {
    stopThread = true;
  }
} 
 

No comments:

Post a Comment