Following is the way by which we can use Singleton Design pattern for multiple users.
public class Singleton {
private volatile static Singleton singleton; //volatile is needed so that multiple thread can reconcile the instance
private Singleton(){
}
public static Singleton getSingleton(){ //synchronized keyword has been removed from here
if(singleton = = null)
{ //needed because once there is singleton available no need to aquire monitor again & again as it is costly
synchronized(Singleton.class)
{
//this is needed if two threads are waiting at the monitor at the time when singleton was getting instantiated
if(singleton==null)
{
singleton= new Singleton();
}
}
}
return singleton;
}
}
No comments:
Post a Comment