Singleton in java, Doubly Locked Singleton class/ Lazy initialization, enum singleton, eager initialization in static block


Contents of page :
  • Singleton class in java?
  • 1) Creating Singleton class in java>
    • Program to create Singleton class/ Lazy initialization>

  • 2) Program to create Doubly Locked Singleton class/ Lazy initialization in java>
    • Let’s discuss in detail about logic of Doubly Locked Singleton class>
    • Understanding one more important concept >

  • 3) Creating Enum Singleton class in java>
  • Singleton enum - Are best way to create Singleton
  • Singleton enum  are also thread safe.
    • Steps >
    • Program to create Enum Singleton class>

  • 4) Singleton eager initialization in java>

  • 5) Singleton eager initialization in static block in java>

  • 6) Singleton in Serialization and DeSerialization in java >


Singleton class in java?
Singleton class means only one instance of class can exist.


1) Creating Singleton class in java>

creating INSTANCE variable -
Make it private > So that INSTANCE variable cannot be accessed outside class.
Make it static > So that INSTANCE variable can be accessed in static methods of class.
Make it Singleton type> So that INSTANCE variable can be refer to Singleton object.
  
creating private constructor-
Make it private > so that class can't be instantiated outside this class.

creating getInstance method -
Method which will return instance (only instance) of Singleton class.
Method will perform double check and ensure no two threads form more than one instance.

Method is public so that it could be accessed outside class.
Method is static so that it could be accessed without creating instance of class.

Use synchronized block inside method-so that 2 threads don’t create more than 1 instance of class concurrently.


This is also known as lazy initialization.

Program to create Singleton class/ Lazy initialization in java>
/**
* Singleton class - with Double checked Locking
*/
class Singleton {
   //private > So that INSTANCE variable cannot be accessed outside class.
   //static > So that INSTANCE variable can be accessed in static methods of class.
   private static Singleton INSTANCE;
   /**
   * private constructor - so that class can't be instantiated outside this
   * class
   */
   private Singleton() {
   }
   /**
   * Method which will return instance (only instance) of Singleton class.
   *
   * Method will perform double check and ensure no two threads form more than one instance.
   *
   * Method is public so that it could be accessed outside class.
   *
   * Method is static so that it could be accessed without creating instance of class.
   *
   * Use synchronized block inside method-so that 2 threads don’t create more
   * than 1 instance of class concurrently.
   */
   public static Singleton getInstance() {
          synchronized (Singleton.class) {
                 if (INSTANCE == null)
                       INSTANCE = new Singleton();
                 return INSTANCE;
          }
   }
   /**
   * instance method of Singleton class.
   */
   public void m() {
          System.out.println("m()");
   }
}
/**
*  Copyright (c), AnkitMittal JavaMadeSoEasy.com
*  Main class
*/
public class SingletonClassTest {
   public static void main(String... a) {
         
          //obj1 will be the reference variable to Singleton instance.
          Singleton obj1 = Singleton.getInstance();
          obj1.m();
         
         
          //Let's conduct test to ensure instance return by
          //Singleton are same
         
          //obj2 will be the reference variable to Singleton instance.
          Singleton obj2 = Singleton.getInstance();
          obj2.m();
         
          //Now, let's do equality test using == operator.
          System.out.println(obj1==obj2); //True
         
   }
}
/*OUTPUT
m()
m()
true
*/

In the later part of program we conducted test to ensure instance return by Singleton class are same.
         
First we obtained 2 references i.e. obj1 and obj2 to instance of Singleton class returned by getInstance() method.

Then equality test was done using == operator.

obj1==obj2 returned True, means two references are referring to same instance of class.



2) Program to create Doubly Locked Singleton class/ Lazy initialization in java>
/**
* Singleton class - with Double checked Locking
*/
class SingletonDoublyLocked {
private static SingletonDoublyLocked INSTANCE;
   /**
   * private constructor
   */
   private SingletonDoublyLocked() {
   }
   public static SingletonDoublyLocked getInstance() {
          //First check - To avoid more than one instance creation of Singleton class.
          if (INSTANCE == null) {
                 synchronized (SingletonDoublyLocked.class) {
                       //Second check - To avoid more than one instance creation of
//Singleton class.
                       if (INSTANCE == null) {
                              INSTANCE = new SingletonDoublyLocked();
                       }
                 }
          }
          return INSTANCE;
   }
   
}


Let’s discuss in detail about logic of Doubly Locked Singleton class>
1.     if (INSTANCE == null) {
2.       synchronized (SingletonDoublyLocked.class) {   
3.          if (INSTANCE == null) {
4.              INSTANCE = new SingletonDoublyLocked();
5.          }
6.    }
Let's say there are two threads t1 and t2 .
Let’s say t1 enters synchronized block reaches line 3, now t2 can’t reach line3 until t1 don’t leave synchronized block. By the time t1 must be waiting at line 2 after (INSTANCE == null) returned true at line 1.
Before leaving synchronized block t1 must have instantiated INSTANCE at line 4. After t1 leaves synchronization block, t2 will enter synchronized block and (INSTANCE == null) at line4 will return false because t1 already instantiated INSTANCE.


Understanding one more important concept >
At this point of time, i guess there might be one question in your mind.
Ques. Is      if (INSTANCE == null)  at line 1 is really needed?
Ans. If an instance of singleton class has already been created, then avoid double checked locking.


3) Creating Enum Singleton class in java>
  • Singleton enum - Are best way to create Singleton
  • Singleton enum  are also thread safe.

Steps >
declare enum.
create private constructor.
Program to create Enum Singleton class>
/*
* Singleton enum - Are best way to create Singleton
* They are also thread safe.
*/
enum SingletonEnum {
       SINGLETON_INSTANCE;
      /** private constructor of enum. */
       private SingletonEnum(){}
}
public class SingletonClassEnumTest {
   public static void main(String...a){
         
          System.out.println(SingletonEnum.SINGLETON_INSTANCE);
         
          //Let's conduct test to ensure instance return by SingletonEnum are same
          System.out.println(SingletonEnum.SINGLETON_INSTANCE==SingletonEnum.SINGLETON_INSTANCE);
                                                                                        //true
         
   }
}
/*OUTPUT
SINGLETON_INSTANCE
true
*/



4) Singleton eager initialization in java>
Creating INSTANCE variable
Make it private > So that INSTANCE variable cannot be accessed outside class.
Make it static > So that INSTANCE variable can be accessed in static methods of class.
Make it final > Once initialized can’t be re initialized.
Make it Singleton type> So that INSTANCE variable can be refer to Singleton object.
  
creating private constructor-
Make it private > so that class can't be instantiated outside this class.

creating getInstance method -
Method which will return instance (only instance) of Singleton class.

class Singleton {
   private static final Singleton INSTANCE=new Singleton();
   /**
   * private constructor - so that class can't be instantiated outside this
   * class
   */
   private Singleton(){
   }
   public static Singleton getInstance() {
                 return INSTANCE;
   }
}


5) Singleton eager initialization in static block in java>

creating static block
  • static blocks are called as soon as class is loaded even before instance of class is created(i.e. before constructor is called)
  • Any code written inside static block is thread safe.

creating INSTANCE variable
Make it private > So that INSTANCE variable cannot be accessed outside class.
Make it static > So that INSTANCE variable can be accessed in static methods of class.
Make it Singleton type> So that INSTANCE variable can be refer to Singleton object.
  
creating private constructor-
Make it private > so that class can't be instantiated outside this class.

creating getInstance method -
Method which will return instance (only instance) of Singleton class.

class Singleton {
   private static Singleton INSTANCE;
  
  
   static{
          INSTANCE=new Singleton();
   }
   /**
   * private constructor - so that class can't be instantiated outside this
   * class
   */
   private Singleton() {
   }
   public static Singleton getInstance() {
                 return INSTANCE;
   }
}


6) Singleton in Serialization and DeSerialization in java>






RELATED LINKS>

What is Serialization in java?


No comments:

Post a Comment