Singleton Design Pattern in Java

Connect with

Singleton Design Pattern in JavaLearn Singleton Design pattern in Java and its different ways of implementation. In Java singleton pattern is popular pattern and used by almost all the developer.

1. Basic of Singleton Design Pattern in Java

Singleton Design pattern in Java is very easy to understand, it has multiple variants of implementation. When a pattern has multiple ways of implementation then it becomes tedious to understand all aspects of implementation. This is a very popular pattern and used by almost all the developer.

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

  • 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.

2. Different Approach of singleton Pattern implementation

There are different approaches of Singleton pattern implementation in Java. And you should know all the approch of its implementation for your project or for your interview prepration.

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

3. Eager initialization approach

This is the easiest method to create a singleton class in Java 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. This is one way of implementation of singleton desing pattern in Java.

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

4. Static block initialization approach

Static block initialization implementation is one way of singleton desing pattern in Java. This 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;
		
	}
}

5. Lazy Initialization approach

In Lazy initialization approach of singleton desing pattern implementation in Java, 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;
    }
}

6. 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. How you do this, see the following java example of singleton desing pattern.

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

7. Double locking approach of Singleton pattern

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

package com.mysoftkey.designpattern.singleton;

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

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

8. 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 ");
  }
}

9. Some interview Questions on Singleton Pattern

Please try to evaluate yourself by answering the following questions for your interview perspective or for your know-how perspectives. These are the common questions for the singleton design patterns, 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

10. Reference

I hope you enjoyed this post of Singleton design pattern in Java, and you can visit design patterns tutorial for more details.
Happy Learning! 🙂


Connect with

Leave a Comment

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