Saturday 10 November 2012

20 java Singleton interview questions

20 singleton interview questions and answers
Q1: What is singleton design pattern?
Ans: Singleton design pattern ensures that at any time there can only be one instance of a class and provide a global point of access to it.

Q2: How will you implement singleton design pattern in java?
Ans: Singleton Pattern implementation:-
  1. Declare a default private constructor.
  2. Declare a private static variable to hold single instance of class.
  3. Declare a public static function that returns the single instance of class.
  4. Do “lazy initialization” in the accessor function.
Q3: Please write code to implement singleton design pattern in java
Ans:
 class Singleton {   
    // 1. Make all constructors private   
    private Singleton() {}   
    // 2.  Declare a private static variable to hold single instance of class   
    private static Singleton INSTANCE = null;   
    // 3.  Declare a public static function that returns the single instance of class    
    public static Singleton getInstance() {   
     // 4. Do "lazy initialization" in the accessor function.   
     if(INSTANCE == null) {   
      INSTANCE = new Singleton();   
     }   
     return INSTANCE;   
    }   
  }   
Q4: In which conditions the above code could lead to multiple instances?
Ans:
 public static Singleton getInstance() {   
   if(INSTANCE == null) { // 1   
     INSTANCE = new Singleton(); // 2   
   }   
   return INSTANCE; // 3   
  }   
If one thread enters getInstance() method and finds the INSTANCE to be null at step 1 and enters the IF block and before it can execute step 2 another thread enters the method and executes step 1 which will be true as the INSTANCE is still null,  then it might lead to a situation (Race condition) where both the threads executes step 2 and create two instances of the Singleton class.

Q5: Above question can be asked in a different way. How can Race condition happen in singleton design pattern in java?
Ans:
 public static Singleton getInstance() {   
   if(INSTANCE == null) { // 1   
     INSTANCE = new Singleton(); // 2   
   }   
   return INSTANCE; // 3   
  }   
If one thread enters getInstance() method and finds the INSTANCE to be null at step 1 and enters the IF block and before it can execute step 2 another thread enters the method and executes step 1 which will be true as the INSTANCE is still null,  then it might lead to a situation (Race condition) where both the threads executes step 2 and create two instances of the Singleton class.

Q6: Write code to recreate Race condition in singleton design pattern in java?
Ans:
 // Recreate threading issue during instantiation of Singleton class   
  class Singleton {   
      // 1. Make all constructors private   
      private Singleton() {}   
      // 2.  Declare a private static variable to hold single instance of class   
      private static Singleton INSTANCE = null;   
      // 3.  Declare a public static function that returns the single instance of class   
      public static Singleton getInstance() {   
        if(INSTANCE == null) {   
         try {   
          // If there is delay in creation of object then the threads might create multiple instances   
          Thread.sleep(10);   
          INSTANCE = new Singleton();   
         }   
         catch (InterruptedException ie) {   
           ie.printStackTrace();   
         }      
        }   
        return INSTANCE;   
       }   
  }   
  public class SingletonThreadingTest implements Runnable   
  {   
      public void run() {              
       System.out.println("Singleton instance id :"+Singleton.getInstance());   
      }   
      public static void main(String[] args)   
      {   
          System.out.println("Singleton Test!");   
          SingletonThreadingTest sei1 = new SingletonThreadingTest();   
          Thread thread1 = null;   
          for(int i=0; i< 2;i++) {   
              thread1 = new Thread(sei1);   
              // might create mutliple instances of Singleton class   
              thread1.start();   
          }   
      }   
  }   

 Q7: What is lazy initilization in Singleton design pattern?
 Ans: Lazy initialization happens when the initialization of the Singleton class instance is delayed till its static  getInstance() is called by any client program. And initialization of the Singleton class takes place inside the getInstance() method.

Q8: What is Eager initilization in Singleton design pattern?
Ans: Eager initilization happens when we eagerly initialize the private static variable to hold the single instance of the class at the time of its declaration.

Q9: Write code to implement eager initilization in Singleton design pattern?
Ans:
 // Eager instantiation of Singleton class   
  class Singleton {   
      // 1. Make all constructors private   
      private Singleton() {}   
      // 2.  Eagerly declare a private static variable to hold single instance of class   
      private static Singleton INSTANCE = new Singleton();   
      // 3.  Declare a public static function that returns the single instance of class   
      public static Singleton getInstance() {   
          return INSTANCE;   
      }   
  }   

Q10: How can we prevent race condition in singleton design pattern?
Ans: We can do it in three ways:-
1) By synchronizing the getInstance() method
2) By using eager initialization of instance
3) By using double checked locking method

Q11: What is the drawback of synchronizing the getInstance() method?
Ans: It will decrease the performance of a multithreaded system as only single thread can access the getInstance method at a time. Also synchronizing a method has its own overheads.

Q12: What can be the drawback of using eager initialization of instance?
Ans: If our application doesn't always creates and uses the singleton instance and overhead of creation of singleton instance is a major point of concern then we can avoid creating the instance of the class eagerly.

Q13: Explain double checked locking method?
Ans: Another way to prevent race condition issue is to use ‘Double checked Locking method’ to reduce the use of synchronization in getInstance() method. It is used to reduce the overhead of acquiring a lock by first testing the locking criterion (the 'lock hint') without actually acquiring the lock. Only if the locking criterion check indicates that locking is required does the actual locking logic proceed. Its called double checked as we check the nullability of INSTANCE twice.

Q14: How will you implement double checked locking method?
Ans:
 // Double checked locking method   
  class Singleton {   
      // 1. Make all constructors private   
      private Singleton() {}   
      // 2.  volatile keyword ensures that multiple threads handle the INSTANCE variable   
      //   correctly when it is being initiaized.   
      private volatile static Singleton INSTANCE = null;   
      // 3.  method is not made synchronized   
      public static Singleton getInstance() {   
          // check that INSTANCE is initialized and if not then enter   
          // synchronized block   
          if(INSTANCE == null) {   
              synchronized(Singleton.class) {   
                  // inside the block check again for initialization   
                  if(INSTANCE == null) {   
                      INSTANCE = new Singleton();   
                  }   
              }   
          }   
          return INSTANCE;   
      }   
  }   

Q15: Can we get multiple instances of a singleton class by cloning?
Ans: Yes we can. It can happen in a scenario where the Singleton class extends from a class which implements Cloneable interface and provides implementation of clone() method. So now we can clone the instance by calling the Object class's clone() method on the singleton instance.


Q16: Show how we can create clone of a singleton class?
Ans:
 class SingletonSuper implements Cloneable {  
         public Object clone() throws CloneNotSupportedException {  
                 return super.clone();  
         }  
 }  
 class Singleton extends SingletonSuper {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = new Singleton();  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
                 return INSTANCE;  
          }  
 }  
 public class SingletonCloningTest  
 {  
         public static void main(String[] args) throws Exception  
         {  
                 System.out.println("Singleton Test!");  
                 System.out.println("Singleton Instance:"+Singleton.getInstance());  
                 System.out.println("Singleton clone:"+Singleton.getInstance().clone());  
         }  
 }  

Q17: How can we prevent cloning in singleton?
Ans: We can override the Object class's clone() method to throw the CloneNotSupportedException exception.
 class SingletonSuper implements Cloneable {  
         public Object clone() throws CloneNotSupportedException {  
                 return super.clone();  
         }  
 }  
 class Singleton extends SingletonSuper {  
          // 1. Make all constructors private  
          private Singleton() {}  
          // 2.   Declare a private static variable to hold single instance of class  
          private static Singleton INSTANCE = new Singleton();  
          // 3.   Declare a public static function that returns the single instance of class   
          public static Singleton getInstance() {  
                 return INSTANCE;  
          }  
          public Object clone() throws CloneNotSupportedException {  
                 // throw CloneNotSupportedException if someone tries to clone the singleton object  
                 throw new CloneNotSupportedException();  
          }  
 }  
 public class SingletonPreventCloningTest  
 {  
         public static void main(String[] args) throws Exception  
         {  
                 System.out.println("Singleton Test!");  
                 System.out.println("Singleton Instance:"+Singleton.getInstance());  
                 // will throw exception if clone method is called  
                 System.out.println("Singleton clone:"+Singleton.getInstance().clone());  
         }  
 }  

Q18: Why do we have private constructors in singleton class?
Ans: A singleton can only have one instance. By making its constructors private we prevent creation of multiple instances of the class.

Q19: Give some use cases where we can use Singleton pattern?
Ans: Classes implementing Thread Pools, database Connection pools, caches, loggers etc are generally made Singleton so as to prevent any class from accidently creating multiple instances of such resource consuming classes.

Q20: If we load a spring application context twice how many instances of a singleton declared bean will there be in the JVM?
Ans: Two. As singleton beans are singletons at application context level.

Read more about Singleton pattern from the below link:-
http://en.wikipedia.org/wiki/Singleton_pattern

5 comments:

  1. One more question we can add, how will you achieve Singleton in a clustered environment?

    ReplyDelete
  2. My singleton design pattern tutorial with code sample could be of use to few readers.

    ReplyDelete
  3. These are great, thanks so much. Never seen so many questions for a singleton before. More good ones right over here:

    http://www.programmerinterview.com/index.php/design-pattern-questions/design-pattern-interview-questions-and-answers/

    ReplyDelete
  4. Why do we have private constructors in singleton class?
    Ans: No class can extend your class...
    If any class contains private constructor, those classes are not extendable.
    Please correct your answer.

    ReplyDelete
  5. Ni Hau,


    10/10 !!! Thank you for making your blogs an embodiment of perfection and simplicity. You make everything so easy to follow.


    I`ve been wondering how to make a copyright protection for a jar file? OK...
    I know that "jar" has some
    sealing mechanism, but I was wondering if it`s possible to make some kind of expiration time? Kind of getting current date, start counting days then after, say, 10 days it disables the functionalites....But my ideas came with a serialized file or just some hidden file... The bad is, that the file can be find and modified.. so this falls. My final idea was to make some kind of connection to my host site, retrieve a key from it or report the usage to it, or read a file from it... then expires... but what if there is no network :( So... any good suggestions?





    But nice Article Mate! Great Information! Keep up the good work!


    Thanks a heaps,
    Ajeeth Kapoor

    ReplyDelete

/* */