Saturday, 1 March 2014

volatile : Concurrency Support

When a variable is volatile, it is guaranteeing that it will not be cached and that different threads will see the updated value. However, not marking it volatile does not guarantee the opposite.

The Java Language Specification indicates that for optimal speed, individual threads are permitted to keep a working copy of shared member variables and only reconcile them when a thread enters or leaves a synchronized block of code.

Example
class VolatileEx extends Thread{
 boolean flag = true;

 public void run(){
  while(flag){
  }
  System.out.println("Came out of the loop");
 }

 public static void main(String args[]) throws Exception{
  VolatileEx t1 = new VolatileEx();
  t1.start();
  Thread.sleep(1000);
  t1.flag = false;
  System.out.println("Flag is set to " + t1.flag);
 }
}
 Output  
Program goes to the infinite loop. Even you set the flag to false, thread keeps using its local copy of flag, which is true. This problem is solved by volatile keyword.   

See the below example, we declared the flag is volatile, so threads will see the updated value of the variable every time. I.e, whenever thread wants to update the variable value, it reads from the shared memory and update the value, and push back the updated value to the shared memory. No caching is done.

Example
class VolatileEx extends Thread{
 volatile boolean flag = true;

 public void run(){
  while(flag){
  }
  System.out.println("Came out of the loop");
 }

 public static void main(String args[]) throws Exception{
  VolatileEx t1 = new VolatileEx();
  t1.start();
  Thread.sleep(1000);
  t1.flag = false;
  System.out.println("Flag is set to " + t1.flag);
 }
}
   
Output

Came out of the loop
Flag is set to false



Give up resources                                                 Synchronization                                                 Home

No comments:

Post a Comment