September 8, 2020

Singleton Design Pattern Implementaion in Java

In this post, I am trying to explain singleton design pattern, using java programmig language.

Source Code  of Singleton desing pattern.

There are two ways which we can do it.

We can use an Inner static class to keep a final instance of our target class.

Or, we can use double null-check with synchronized block to guard against multiple instance creation.

You can see my live coding video on youtube for better explaination. [ Live Coding of singleton Design Pattern ]

In the case of using static inner class.

The instance is created when the inner class is loaded for the first time.

And, this instance is final and static so, there is always going to be only one instance of this class in entire application.

public final class SingletonStaticWay {
     static class Inner {
         private final static SingletonStaticWay instance = new SingletonStaticWay();
     }

     public static SingletonStaticWay instance(){
         return Inner.instance;
     }
}

We declare the class as final to prevent subclassing of this Singleton class.

 

In the other method of creating an inner class, we use double check for null case and use synchronized block to prevent multiple thread from creating more than one instances.

 

public final class Singleton{
     //This code will create an object on the class load.. which is not needed
     // and it is not efficient
     //private static final Singleton singleton = new Singleton();

     private static Singleton singleton; 

     private Singleton(){}

     // Threads will wait in a queue to read the instance object.
     //Although, the instance has been already created
     //public static synchronized Singleton instance(){
     public static Singleton instance(){
     if(null == singleton) {
         synchronized(Singleton.class){
                 if(null == singleton)
             singleton = new Singleton();
         }
     }
         return singleton;
     }
}