Volatile keyword in Java is used as an indicator to Thread that do not cache value of this variable and always read it from main memory.
Example using Singleton:
public class Singleton{
private static volatile Singleton _instance;
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.
Notes:
1. Volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
2. Volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.
Example using Singleton:
public class Singleton{
private static volatile Singleton _instance;
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.
Notes:
1. Volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
2. Volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.
1 comment:
nice post,thanks a lot :)
Post a Comment