Java Singleton Interviw Questions

What is singleton pattern?

Singleton is a most commonly used design pattern and is used when we want one and only one instance of a class per JVM. Classes developed to perform business logic is good example of Singleton class.

Name one singleton class in Java?


How we can create a class singleton?

To make any class singleton, we need to consider or implement following-

  1. Private or protected constructor- We need to make the constructor of a class private so that no one from outer world can call a “new”.
  2. Create a private static instance of the class.
  3. Create a public static method which will return the instance created.

Write an example on how to create a singleton class?

Below is the sample code-

Explain early and lazy loading of singleton class?

We can have an early and lazy loading of a singleton class. In case of early loading, an object of singleton class is instantiated while loading of  a class where as in case of lazy loading object is crated on first request. While using lazy loading we need to consider synchronization as ignoring it might end up with having multiple objects in multi threaded applications.

Explain double check  locking in singleton class?

Synchronizing complete method in case of lazy loading of a singleton classes can have a performance issues in multi threading applications so double check locking is a way to synchronize a block and check if the instance is null twice. Refer below example

Can we break singleton?

Answer- Yes, one can create multiple objects using

  1. Serialization/deserialization if singleton class is marked as serializable. So we should not mark singleton class as serializable and  in case class is serializable via inheritance, override readObject() method and throw Non serializable exception.
  2. Cloning- if singleton class is marked as cloneable. So we should not mark singleton class as Cloneable and if class is cloneable (by parent class), override clone method and throw CloneNotSupported exception.
  3. Using reflection as reflection can access private fields. So we can apply check in constructor and throw exception if instance is not created from constructor.


Like us on Facebook