Singleton Design Pattern Using Java

 


Introduction


This tutorial will highlight the importance of Singleton Design pattern using java implementation. It explains various ways of implementation with flaw in the implementation.

Singleton design pattern is one of the most common patterns you will see in Java applications and it’s also used heavily in core Java libraries. Singleton Design Pattern is having critical importance in Design pattern and comes under Creational Design pattern.

Using Singleton Design pattern we used to make sure there will be only one instance of that class created and no other instances created in any case.

Example: Please find example of Singleton Design Pattern below –

  • Logger is a best example of Singleton Design Patter as we store information in one loge file.
  • java.lang.Runtime is example of Singleton in Java API.
  • java.awt.Toolkit is example of Singleton in Java API.
  • java.sql.DriverManager is example of Singleton in Java API.
  • java.sql.Connection is example of Singleton in Java API.

There are many ways to implement Singleton Design Pattern, please find below –


Example:Eager initialization


This is a very basic Singleton Design Pattern Implementation where object will be created at the time of class loading on JVM.

Please find source code below –

KWSingletonDesignPatternExample1.java: This class will instantiate object at the time of class loading to JVM.

package com.singletondesignpattern;

/**
 * This class helps to implement Singleton Design Pattern using simple way using
 * private Constructor.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPatternExample1 {
    // Instantiate Object to instantiate when class loaded
    private static KWSingletonDesignPatternExample1 kwSingletonDesignPatternExample1 = new KWSingletonDesignPatternExample1();

    /**
     * Private constructor so it would not call from outside.
     */
    private KWSingletonDesignPatternExample1() {

    }

    /**
     * This method helps to instantiate KWSingletonDesignPatternExample1 object.
     *
     * @return KWSingletonDesignPatternExample1
     */
    public static KWSingletonDesignPatternExample1 getInstance() {
        
        return kwSingletonDesignPatternExample1;
    }

}

KWSingletonDesignPaternInvocation.java: This class helps to invoke above Singleton Design Pattern Implementation.

 

package com.singletondesignpattern;

/**
 * This class helps to invoke Singleton Design Pattern examples.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPaternInvocation {

    public static void main(String[] args) {
        // Call Simple Singleton Design Patter Example
        invokeKWSingletonDesignPatternExample1();
    }
    /**
     * This method helps to invoke Singleton Design Pattern Example1.
     */
    public static void invokeKWSingletonDesignPatternExample1() {

        System.out.println("*******invokeKWSingletonDesignPatternExample1*****");
        System.out.println("First Instantce :" +
        KWSingletonDesignPatternExample1.getInstance());
        System.out.println("Second Instantce :" +
        KWSingletonDesignPatternExample1.getInstance());
        System.out.println("Third Instantce :" +
        KWSingletonDesignPatternExample1.getInstance());
    } 

}

Output: After executing KWSingletonDesignPaternInvocation.java class, we will get below output and looks like creating only one object.

*******invokeKWSingletonDesignPatternExample1*****
First Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample1@3238c403
Second Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample1@3238c403
Third Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample1@3238c403

 

This implementation is effective when there is only one JVM and class loaded only on one JVM. if there are multiple JVM then this class will be loaded in multiple JVM and will instantiate multiple object.


Example: Static Block Initialization


Static block initialization is same as above example except exception handling. Static Block is also executed at the time of class loading on JVM. Please find source code below –

KWSingletonDesignPatternExample2.java: This class has Singleton Design Pattern Implementation using Static block.

package com.singletondesignpattern;

/**
 * This class helps to implement Singleton Design Pattern using Static Block.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPatternExample2 {
    // Instantiate Object to instantiate when class loaded
    private static KWSingletonDesignPatternExample2 kwSingletonDesignPatternExample2 = null;

    /**
     * Private constructor so it would not call from outside.
     */
    private KWSingletonDesignPatternExample2() {

    }
    // Static block to instantiate object
    static{
        try{
            // Instantiate Object
            kwSingletonDesignPatternExample2 = new KWSingletonDesignPatternExample2();
            
        }catch(Exception e){
            throw new RuntimeException("Exception occured in creating singleton instance");
        }
        
    }

    /**
     * This method helps to instantiate KWSingletonDesignPatternExample2 object.
     *
     * @return KWSingletonDesignPatternExample2
     */
    public static KWSingletonDesignPatternExample2 getInstance() {
        
        return kwSingletonDesignPatternExample2;
    }

}

KWSingletonDesignPaternInvocation.java: his class helps to invoke above Singleton Design Pattern Implementation.

package com.singletondesignpattern;

/**
 * This class helps to invoke Singleton Design Pattern examples.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPaternInvocation {

    public static void main(String[] args) {
        // Call Simple Singleton Design Patter Example
        invokeKWSingletonDesignPatternExample2();
    }
    /**
     * This method helps to invoke Singleton Design Pattern Example2.
     */
    public static void invokeKWSingletonDesignPatternExample2() {
        
        System.out.println("*******invokeKWSingletonDesignPatternExample2*****");
        System.out.println("First Instantce :" +
        KWSingletonDesignPatternExample2.getInstance());
        System.out.println("Second Instantce :" +
        KWSingletonDesignPatternExample2.getInstance());
        System.out.println("Third Instantce :" +
        KWSingletonDesignPatternExample2.getInstance());
    }  

}

Output: After executing KWSingletonDesignPaternInvocation.java class, we will get below output and looks like creating only one object.

*******invokeKWSingletonDesignPatternExample2*****
First Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample2@2400218d
Second Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample2@2400218d
Third Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample2@2400218d

This implementation is effective when there is only one JVM and class loaded only on one JVM. if there are multiple JVM then this class will be loaded in multiple JVM and will instantiate multiple object.

 


Example: Lazy Initialization


This is a very simple way of Singleton Design Pattern implementation. Lazy Initialization instances object when ever getInstance method invoked. Source code available below –

KWSingletonDesignPatternExample3.java: Singleton Design Pattern Implementation class.

package com.singletondesignpattern;

/**
 * This class helps to implement Singleton Design Pattern using simple way using
 * private Constructor.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPatternExample3 {
    // Instantiate Object to instantiate when class loaded
    private static KWSingletonDesignPatternExample3 kwSingletonDesignPatternExample3 = null;

    /**
     * Private constructor so it would not call from outside.
     */
    private KWSingletonDesignPatternExample3() {
        
        
    }

    /**
     * This method helps to instantiate KWSingletonDesignPatternExample1 object.
     *
     * @return KWSingletonDesignPatternExample1
     */
    public static KWSingletonDesignPatternExample3 getInstance() {
        
        if(kwSingletonDesignPatternExample3 == null){
        
            // Call constructor to instantiate Object
            kwSingletonDesignPatternExample3 = new KWSingletonDesignPatternExample3();
        }        
        
        return kwSingletonDesignPatternExample3;
    }

}

 

KWSingletonDesignPaternInvocation.java: This class helps to invoke above Singleton Design Pattern Implementation.

package com.singletondesignpattern;

/**
 * This class helps to invoke Singleton Design Pattern examples.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPaternInvocation {

    public static void main(String[] args) {
        // Call Simple Singleton Design Patter Example
        invokeKWSingletonDesignPatternExample3();

    }

    /**
     * This method helps to invoke Singleton Design Pattern Example1.
     */
    public static void invokeKWSingletonDesignPatternExample3() {

        System.out.println("First Instantce :" +
        KWSingletonDesignPatternExample3.getInstance());
        System.out.println("Second Instantce :" +
        KWSingletonDesignPatternExample3.getInstance());
        System.out.println("Third Instantce :" +
        KWSingletonDesignPatternExample3.getInstance());
    }

}

 

Output: After executing KWSingletonDesignPaternInvocation.java class, we will get below output and looks like creating only one object.

First Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample3@507d811a
Second Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample3@507d811a
Third Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample3@507d811a

 

Above Singleton Design Pattern Implementation is very basic and useful when it is single thread program but it would not work when it is multi threading environment. There are a way, we can Instantiate multiple object invoking  KWSingletonDesignPatternExample3 class in the same time from different source. Also, using clone we can break above code to instantiate multiple object.

 


Example:Thread Safe Singleton


Singleton Design pattern implementation for multi threaded environment can be implemented using synchronized method technique. getInstance method will be synchronized so only thread can get the lock for this method.

Please find source code below –

KWSingletonDesignPatternExample4.java: This class implemented singleton Design Pattern using synchronized method technique. This way of implementation would not allow multiple thread to get access on getInstance method.

package com.singletondesignpattern;

/**
 * This class helps to implement Singleton Design Pattern using synchronized
 * method. Only one thread will get the lock on getInstance method. private
 * Constructor.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPatternExample4 {
    // Instantiate Object to instantiate when class loaded
    private static KWSingletonDesignPatternExample4 kwSingletonDesignPatternExample4 = null;

    /**
     * Private constructor so it would not call from outside.
     */
    private KWSingletonDesignPatternExample4() {

    }

    /**
     * This method helps to instantiate KWSingletonDesignPatternExample4 object.
     * Only one thread will get the lock as we made method as synchronized.
     *
     * @return KWSingletonDesignPatternExample4
     */
    public static synchronized KWSingletonDesignPatternExample4 getInstance() {

        if (kwSingletonDesignPatternExample4 == null) {

            // Call constructor to instantiate Object
            kwSingletonDesignPatternExample4 = new KWSingletonDesignPatternExample4();
        }

        return kwSingletonDesignPatternExample4;
    }

}

KWSingletonDesignPaternInvocation.java: This class helps to invoke above Singleton Design Pattern Implementation.

package com.singletondesignpattern;

/**
 * This class helps to invoke Singleton Design Pattern examples.
 *
 * @author dknitk
 *
 */
public class KWSingletonDesignPaternInvocation {

    public static void main(String[] args) {
       
        // Call Simple Singleton Design Patter Example
        invokeKWSingletonDesignPatternExample4();

    }
    /**
     * This method helps to invoke Singleton Design Pattern Example4.
     */
    public static void invokeKWSingletonDesignPatternExample4() {

        System.out.println("*******invokeKWSingletonDesignPatternExample4*****");
        System.out.println("First Instantce :" + KWSingletonDesignPatternExample4.getInstance());
        System.out.println("Second Instantce :" + KWSingletonDesignPatternExample4.getInstance());
        System.out.println("Third Instantce :" + KWSingletonDesignPatternExample4.getInstance());
    }

}

 

Output: After executing KWSingletonDesignPaternInvocation.java class, we will get below output and looks like creating only one object.

 

*******invokeKWSingletonDesignPatternExample4*****
First Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample4@62918c34
Second Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample4@62918c34
Third Instantce :com.singletondesignpattern.KWSingletonDesignPatternExample4@62918c34

 

Above example is perfect for singleton design pattern as it would to allow multiple thread to instantiate multiple object. As, it is a good example but it is also having one flaw and performance issue.

Synchronize method is costly and it is block whole method. There is a synchronized block which can resolve issue.

Updated getInstance method using synchronized block and double check.

/**
     * This method helps to instantiate KWSingletonDesignPatternExample4 object.
     * Only one thread will get the lock as we made method as synchronized.
     *
     * @return KWSingletonDesignPatternExample4
     */
    public static KWSingletonDesignPatternExample4 getInstance() {

        if (kwSingletonDesignPatternExample4 == null) {
            
            synchronized (KWSingletonDesignPatternExample4.class) {
                if (kwSingletonDesignPatternExample4 == null) {
                    // Call constructor to instantiate Object
                    kwSingletonDesignPatternExample4 = new KWSingletonDesignPatternExample4();
                }                
            }
            
        }
        return kwSingletonDesignPatternExample4;
    }

Hope, you understand the concept and enjoyed reading. Please provide your valuable comments. Thanks 🙂

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *