ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

Example of volatile keyword in Java

To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java.

 

/**

 * Java program to demonstrate where to use Volatile keyword in Java.

 * In this example Singleton Instance is declared as volatile variable to ensure

 * every thread see updated value for _instance.

 *

 * @author Javin Paul

 */

public class Singleton{

private static volatile Singleton _instance; //volatile variable

 

public static Singleton getInstance(){

 

   if(_instance == null){

            synchronized(Singleton.class){

              if(_instance == null)

              _instance = new Singleton();

            }

 

   }

   return _instance;

 

}

 

If you look at the code carefully you will be able to figure out:

1) We are only creating instance one time

2) We are creating instance lazily at the time of first request comes.

 

If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.

Related Posts Plugin for WordPress, Blogger...
Flag Counter