Singleton Design Pattern in Java

Connect with

Oracle Java
Singleton Design pattern is very easy and straight forward with multiple variant of implementation. When a pattern have multiple way of implementation then it become tedious to understand all aspect of implementation. This is very popular pattern and used by almost all the developer.

1. Basic concept and building block

Please follow the basic concept and building block to implement Singleton Design pattern.

  • Make Constructor private: Private constructor to restrict instantiation of the class from out side of class it means from other classes.
  • Private static variable within same class .
  • Public static method that returns the instance of the class from outside of the singleton class to get reference of singleton.

There are different approaches of Singleton pattern implementation.

  • Eager initialization
  • Static block initialization
  • Lazy Initialization
  • Thread Safe Singleton
  • Enum Singleton

2. Eager initialization approach

This is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it. The instance of Singleton Class is created at the time of loading class.

public class Singleton {
 
    private static Singleton instance = new Singleton();;
     
    private Singleton(){}
     
    public static synchronized Singleton getInstance(){
        return instance;
    }
}

3. Static block initialization approach

Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block, which call while loading of class at load time.

/**
 * 
 * @author ranjeet.jha
 *
 */
public class Singleton {

	public static Singleton instance;
	
	// to prevent calling from out side of this class
	private Singleton() {
		
	}
	
	//static block initialization for exception handling
    static{
        try{
            instance = new Singleton();
        }catch(Exception e){
            throw new RuntimeException("Exception occured in creating singleton instance");
        }
    }
     
	public static Singleton getInstance()  {
		return instance;
		
	}
}

4. Lazy Initialization approach

In Lazy initialization getInstance method will call whenever first request comes in, it means instance of class create when ask for first request.

public class Singleton {
 
    private static Singleton instance = null;
    
    private Singleton(){}
     
    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

5. Thread Safe Singleton approach

The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time.

public class Singleton{
 
    private static Singleton instance;
     
    private Singleton(){
    }
     
    public static synchronized Singleton getInstance(){
     if(instance == null){
       instance = new Singleton();
     }
       return instance;
    }
     
}

6. Double locking approach

In the double locking way or approach, you can check the creation of object twice so that no concurrent thread will not able to create simultaneously.

package com.mysoftkey.designpattern.singleton;

/**
 * 
 * @author ranjeet.jha
 *
 */
public class Singleton {

  public static Singleton instance;
	
   // to prevent calling from out side of this class
   private Singleton() {
		
   }
   
  public static Singleton getInstance()  {
   if (instance == null) {
     synchronized (Singleton.class) {
       if (instance == null) {
	 instance = new Singleton();
	}
     }
   }
   return instance;
		
  }
}

7. Enum Singleton approach

Joshua Bloch suggests the use of Enum to implement Singleton design pattern, as Java ensures that any enum value is instantiated only once in a Java program. this way we can overcome thee issue in reflection.

package com.mysoftkey.designpattern.singleton;

/**
 * @author ranjeet
 *
 */
public enum SingletonEnum {

  INSTANCE;
    
  public static void hello(){
     System.out.println("pring hello ");
  }
}

8. Some interview Questions

Please try to evaluate yourself by answering following question in the interview. These are the common question which use to ask by interview in the most of the interview. You know, everyone use this singleton design pattern so interviewer try to find how much he/she know what they use.

  • What is Singleton class? Have you used Singleton before?
  • is any Serialization and Singleton issue?
  • Using Reflection can we destroy Singleton Pattern?
  • Bill Pugh Singleton Implementation or inner static helper class?
  • Can we implement Serializable interface in Singleton class?
  • can you tell me where singleton used in JDK?
  • can you tell me where singleton used in Spring Framework?
  • Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
  • Can you write code for getInstance() method of a Singleton class in Java?
  • Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer?
  • What is double checked locking in Singleton?
  • How do you prevent for creating another instance of Singleton using clone() method?
  • How do you prevent for creating another instance of Singleton using reflection?
  • Why you should avoid the singleton anti-pattern at all and replace it with DI?

we will discuss one by one in next article

8. References


Connect with

Leave a Reply

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