Thursday, June 3, 2010

Singleton - Multiple Users [Thread Safe]

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;
    }
}

1 comment:

  1. i have a util class where which don't have access to session object. i want to initialize this util class and want to get that instance throughout application. here every user need to have his own instance of that util class how to achieve this.

    please help me

    ReplyDelete