Singleton Design Pattern with Example and Program Code : Design pattern Interview Question

In this post we are going to learn about the singleton design pattern . It is the most used design pattern in web applications . So if you write design pattern in your CV , then make sure you are familiarized with Singleton
Pattern . For experienced people ,the most common question asked by the interviewer is to write down the code of the Singleton Pattern . Let us discuss that first .

Points to remember while creating a singleton class

Suppose we are creating a singleton class JavaHungry . It means only one  and only one instance of JavaHungry class we  can have at any point of execution in the application code  

*   We  should create a static variable so that it can hold one single instance of our class .
  
         private static JavaHungrySingleton  uniqueInstance ;

*   We should declare the constructor private so that  only Class itself can instantiate the object . Outside
     classes will not be able to see  the class constructor .

private   JavaHungrySingleton(){}

*  Then the main work  to write the method which returns the instance of the class , let the name of the    
    method be  getInstance() .

   Here in this method implementation we created the class JavaHungrySingleton .

  The return type should be of the class object . But there is possibility that two threads simultaneously try to
  access the method and we might end up with two different class objects , thats why method is     synchronized . In other words , By adding synchronized keyword to the method , we force every thread
  to wait for its turn before it can enter the method .  So that , two threads do not enter the method at the    
  same time .
   So we have set up the framework for the singleton method ,which  upto now  looks like

public static synchronized  JavaHungrySingleton   getInstance()
{
    1.               // some code
}

    Now we need to write  code for the method , that is line 1 //some code .

    So to achieve uniqueinstance , first and foremost important thing to check whether the object of the class
    is already in existence or not . We make sure , by putting condition

Pseudo code to achieve singleton 

   if  uniqueinstance is NULL
   
                  then create the object of the class
   else
                      return uniqueinstance ;

    What  above code is trying to achieve is to make sure there should be atmost one and only one instance of     the  class at any given time .      

        So , code in the method will be look like this
 
if (uniqueInstance ==null )
{
    uniqueInstance=new JavaHungrySingleton();
}
return uniqueInstance ;


Interviewer may ask the Class diagram of the Singleton class you created , so below is the class diagram of the JavaHungrySingleton class .


singleton design pattern in java code with example





















So  all the code summed up in the below JavaHungrySingleton Class


public class JavaHungrySingleton
{
    
    private static JavaHungrySingleton  uniqueInstance;
    
    private JavaHungrySingleton(){}
    
    public static  synchronized  JavaHungrySingleton  getInstance()
    {
        if (uniqueInstance ==null )
        {
            uniqueInstance=new JavaHungrySingleton();
        }
        return uniqueInstance ;
    }
    
    // other useful methods here
}


Now after writing the code , interviewer may asked to write the code using early initialization . To do that ,first we need to understand the difference between lazy initialization and early initialization .

Lazy Initialization :    We create the object of the class only when it is about to use in the program code .
                                    We are calling it lazy because we wait till the last moment to have an object.

Early Initialization :  In this we create the object when the class is getting loaded into the JVM . Eager
                                   intialization is helpful if our application always create and use the Singleton class .



//Code for the Early initialization will be :


public class JavaHungrySingleton
{
    
    private static JavaHungrySingleton  uniqueInstance  =  new JavaHungrySingleton();
    
    private JavaHungrySingleton(){}
    
    public static  JavaHungrySingleton  getInstance()
    {
        return  uniqueInstance ;
    }
    
    // other useful methods here
}


There is third way to achieve singleton pattern while removing some overhead from the getInstance() method of the JavaHungrySingleton class . 
For 6-7 years or above  experience , interviewer may ask about the double checked locking .
In double checked locking  first we check if the object is created , if not then we create one using synchronized block.

Below  is the best  Optimized code for the Singleton pattern 


public class JavaHungrySingleton
{
    
    private static  volatile JavaHungrySingleton  uniqueInstance;
    
    private JavaHungrySingleton(){}
    
    public static   JavaHungrySingleton  getInstance()
    {
        if (uniqueInstance ==null )
        {
            synchronized(JavaHungrySingleton.class)
            {
                if (uniqueInstance ==null )
                {
                    uniqueInstance=new JavaHungrySingleton();
                }
            }
        }
        return uniqueInstance ;
    }
    
    // other useful methods here
}
      
If you have any doubts for singletondesign pattern ,mentioned it below in the comments .



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry