What is Singleton Pattern ?
Singleton pattern is used when we want to create only one instance of a class.
A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.
What is a Singleton class? Have you used Singleton class before?
- Singleton is a class which has only one instance in whole application and provides a get Instance() method to access the singleton instance.
- There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access and is used to get free memory and total memory in Java.
Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
- Any class which you want it to make available to whole application and only one instance is viable can be made as a Singleton class.
- One example of this is Runtime class as on whole java application only one runtime environment is possible and so making Runtime as singleton can be considered as right decision.
- Another example is a utility class say for instance ‘Popup’ in ‘GUI application’ where you can show popup with a message. Here you can have one Popup class on whole GUI application where you just need to get instance anytime and call ‘show()’ method with message.
Singleton Pattern Interview Question
What is lazy and early loading of Singleton and how to implement it?
- There are a number of ways to implement Singleton class like using double checked locking or Singleton class with static final instance that can be initialized during class loading.
- The former is called ‘lazy loading’ because Singleton instance is created only when client calls ‘getInstance()’ method while later is called ‘early loading’ because Singleton instance is created when class is loaded into memory.
Give some examples of Singleton pattern from Java Development Kit (JDK).
There are many classes in Java Development Kit which is written using singleton pattern, some of which are as mentioned below:
- Java.lang.Runtime with get Runtime() method
- Java.awt.Toolkit with getDefaultToolkit()
- Java.awt.Desktop with get Desktop()
What is double checked locking in Singleton?
Double checked locking’ in singleton is a technique to prevent the creation of another instance of Singleton when a call is made to the ‘get Instance()’ method in multi-threading environment. In ‘Double checked locking pattern’ as shown in below example, singleton instance is checked two times before initialization.
public static Singleton getInstance()
{
if(_INSTANCE == null)
{
synchronized(Singleton.class)
{
// double checked locking -
// because second check of Singleton instance with lock
if(_INSTANCE == null)
{
_INSTANCE = new Singleton();
}
}
}
return _INSTANCE;
}
‘Double checked locking’ should only be used when you have requirement for ‘lazy initialization’ otherwise use ‘Enum’ to implement ‘singleton’ or ‘simple static final variable’.
Advance Singleton Pattern Interview Question
How do you prevent from creating another instance of Singleton using reflection?
Since constructor of Singleton class is supposed to be private, it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”
How do you prevent from creating another instance of Singleton during serialization?
You can prevent the creation of another instance of singleton during serialization using ‘read Resolve()’ method, since during serialization ‘read Object()’ method is used to create instance and it returns new instance every time but by using ‘read Resolve()’ method you can replace it with original Singleton instance.
Why one should avoid the singleton anti-pattern and replace it with DI?
Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.
Singleton Pattern Interview Question
Why Singleton is anti pattern?
With more and more classes calling ‘get Instance()’ method the code gets more and more tightly coupled, monolithic, not testable and hard to change as well as hard to reuse because of non-configurable and hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call ‘get Instance()’ method less often (i.e. once a while).
In how many ways you can write Singleton Class in Java?
One can implement Singleton pattern in Java in four ways:
- Singleton by synchronizing ‘get Instance()’ method.
- Singleton with ‘public static final’ field initialized during class loading.
- Singleton generated by ‘static’ nested class, also referred as ‘Singleton’ holder pattern.
- From Java 5 onwards, Singleton class in Java can be written using Enum.
How to write thread-safe Singleton in Java?
- Thread safe Singleton usually refers to writing thread safe code which creates one and only one instance of Singleton if called by ‘multiple’ threads at the same time.
- There are many ways to achieve this say for instance by using ‘double checked locking’ technique as shown above and by using ‘Enum’ or ‘Singleton’ initialized by class loader.
Singleton Pattern Interview Question
What’s the difference between a singleton class and a static class?
Static class is one approach to make a class “Singleton”.
We can create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.
The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.
What is a good way to use Singleton Pattern in Java ?
Use Enum.
public enum EasySingleton{
INSTANCE;
}
Another approach is to declare the constructor private and providing a getInstance() method to access the instance as follows :
private static SingletonClass instance = null;
private SingletonClass () {
//constructor code here
}
public static SingletonClass getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
However, the second approach will have issues in multithreaded environment and double checked locking needs to be implemented.
What is double checked locking ?
To implement DCL, you check a volatile field in the common path and only synchronize when necessary:
static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance == new Singleton();
}
}
return instance;
}
Advance Singleton Pattern Interview Question
How to avoid Singleton class instance creation through Reflection ?
o avoid instance creation through reflection, throw exception from constructor.
private Singleton() {
if( Singleton.singleton != null ) {
throw new InstantiationError( “Creating of this object through reflection is not allowed.” );
}
}
How to avoid multiple singleton creation during deserialization ?
Avoid multiple singletons during deserialization using Read Resolve().
protected Object read Resolve() {return instance;}
How to avoid cloning of the Singleton instance ?
To prevent cloning implement Cloneable interface and throw the cloneNotSupportedException from clone() method.
Singleton Pattern Interview Question
Why singleton is considered an Anti-pattern ?
– Singletons aren’t easy to handle with unit tests. You can’t control the instantiation and by their very nature may retain state across invocations.
For that reason the principle of dependency injection is popular.
Frameworks such as Spring control the lifecycle of their objects and often create singletons, but these objects are injected into their dependent objects by the framework. Thus the codebase itself doesn’t treat the objects as singletons.
– By limiting yourself to one instance of an object, the options for threading are limited. Access to the singleton object may have to be guarded (e.g. via synchronization).
What is a Singleton Class ?
Class using which only one object can be created.
What is the use of such a class ?
There could be situations where we need not create multiple objects and hence Singleton can help in saving resources by avoiding creating new objects every time a request is made. Moreover these classes can also be helpful if we want a object to be shared among threads.
Advance Singleton Pattern Interview Question
Are u using Singleton in your code ?
Yes, for Database connection and Property files.
Write the code for a Singleton Class ?
class Singleton {
private static volatile Singleton instance = null;
private Singleton(){}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance== null)
instance = new Singleton();
}
}
return instance;
}
}
Why have we used synchronized here ?
Get Instance method can be accessed from two points simultaneously and in such case 2 instances may get created. Synchronization will make sure that the method gets accessed one by one for each call and the same object is returned for the second call.
Singleton Pattern Interview Question
Why have we declared the instance reference volatile ?
That’s an instruction to JVM that the variable is getting accessed by multiple locations and hence don’t cache it.
Can we make the reference instance non static ?
No , as non static variables cannot be accessed through static methods.
Can we have this pattern implemented using Static Class ?
Though we can implement this behavior using static class , but we should never do it.
Advance Singleton Pattern Interview Question
What are the problems in implementing this patterns using static Class ?
a. We cannot achieve runtime Polymorphism or late binding as Java doesn’t allow overriding static methods.
b. We cannot do lazy initialization as Static members are loaded during class loading only.
c. We cannot serialize as Java doesn’t serialize static members.
Describe in how many ways can you create a singleton pattern?
There are two ways of creating a Singleton pattern.
1. Early Instantiation
It is responsible for the creation of instance at load time.
2. Lazy Instantiation
It is responsible for the creation of instance when required.
Can you write Thread-safe Singleton in Java?
There are many ways to write a Thread-safe singleton in Java.
- Thread-safe Singleton can be written by writing singleton using double-checked locking.
- Another way is, by using static Singleton instance initialized during class loading.
- By using Java enum to create a thread-safe singleton, this is the most straightforward way.
Singleton Pattern Interview Question
Is it possible to create a clone of a singleton object?
Yes, it is possible to create a clone of a singleton object.
Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one Popup class on whole GUI application and anytime just get its instance, and call show() with message.
What is lazy and early loading of Singleton and how will you implement it?
As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls get Instance() method while later is called early loading because Singleton instance is created when class is loaded into memory.
Advance Singleton Pattern Interview Question
What is double checked locking in Singleton?
Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.
public static Singleton getInstance(){ if(_INSTANCE == null){ synchronized(Singleton.class){ //double checked locking - because second check of Singleton instance with lock if(_INSTANCE == null){ _INSTANCE = new Singleton(); } } } return _INSTANCE; }
How do you prevent for creating another instance of Singleton using clone() method?
Preferred way is not to implement Cloneable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.
How do you prevent for creating another instance of Singleton using reflection?
This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”
Singleton Pattern Interview Question
How do you prevent for creating another instance of Singleton during serialization?
You can prevent this by using read Resolve() method, since during serialization read Object() is used to create instance and it return new instance every time but by using read Resolve you can replace it with original Singleton instance. I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranteed of that.
Why you should avoid the singleton anti-pattern at all and replace it with DI?
Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.
How many ways you can write Singleton Class in Java?
I know at least four ways to implement Singleton pattern in Java
- Singleton by synchronizing getInstance() method
- Singleton with public static final field initialized during class loading.
- Singleton generated by static nested class, also referred as Singleton holder pattern.
- From Java 5 on-wards using Enum
Advance Singleton Pattern Interview Question
How to write thread-safe Singleton in Java?
Thread safe Singleton usually ref which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using enum or Singleton initialized by class loader.
How to stop cloning of Singleton class?
It can be stopped by overriding the method and throwing CloneNotSupportedException.
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Clone not allowed");
}
How to stop serialization of Singleton class?
It can be stopped by implementing the read Resolve method the method.
protected Object readResolve() {
return instance;
}
Singleton Pattern Interview Question
How to stop creation of instance through reflection of Singleton class?
It can be stopped by throwing exception in constructor
private Singleton() {
if( Singleton.instance != null ) {
throw new InstantiationError( " Object creation is not allowed." );
}
}
What is Singleton Pattern in C#?
We need to use the Singleton Design Pattern in C# when we need to ensures that only one instance of a particular class is going to be created and then provide simple global access to that instance for the entire application.

As you can see in the above diagram, different clients (NewObject a, NewObject b and NewObject n) trying to get the singleton instance. Once the client gets the singleton instance then they can invoke the methods (Method 1, Method 2, and Method n) using the same instance. If this is confused at the moment then don’t worry we will discuss it with practice.
What are the Advantages of using the Singleton Pattern in C#?
The Advantages of using the Singleton Design Pattern in C# are as follows.
- The first and most important advantage of using the singleton design pattern in C# is that it takes care of concurrent access to the shared resource. That means if we are sharing a resource with multiple clients simultaneously, then concurrent access to that resource is well managed by the singleton design pattern.
- It can be lazy-loaded and also has Static Initialization.
- To share common data i.e. master data and configuration data which is not changed that frequently in an application. In that case, we need to cache the objects in memory.
- As it provides a single global point of access to a particular instance, so it is easy to maintain.
- To reduce the overhead of instantiating a heavy object again and again.
Advance Singleton Pattern Interview Question
What are the Disadvantages of using the Singleton Design Pattern in C#?
The disadvantages of using the Singleton Design Pattern in C# are as follows:
- Unit testing is very difficult because it introduces a global state into an application.
- It reduces the potential for parallelism within a program because to access the singleton instance in a multi-threaded environment, you need to serialize the object by using locking.
Implementation Guidelines of Singleton Design Pattern in C#:
The following are the implementation guidelines for using the singleton design pattern in C#.
- You need to declare a constructor that should be private and parameter less. This is required because it is not allowed the class to be instantiated from outside the class. It only instantiates from within the class.
- The class should be declared as sealed which will ensure that it cannot be inherited. This is going to be useful when you are dealing with the nested class. We will discuss this scenario with an example in our upcoming article.
- You need to create a private static variable that is going to hold a reference to the single created instance of the class if any.
- You also need to create a public static property/method which will return the single-created instance of the singleton class. This method or property first check if an instance of the singleton class is available or not. If the singleton instance is available, then it returns that singleton instance otherwise it will create an instance and then return that instance.
Example of the Singleton Design Pattern using C#
Let us understand the Singleton Design pattern in C# with an example. There are many ways, we can implement the Singleton Design Pattern in C# are as follows.
- No Thread-Safe Singleton design pattern.
- Thread-Safety Singleton implementation.
- The Thread-Safety Singleton Design pattern implementation using Double-Check Locking.
- Thread-Safe Singleton Design pattern implementation without using the locks and no lazy instantiation.
- Fully lazy instantiation of the singleton class.
- Using .NET 4’s Lazy<T> type.
Singleton Pattern Interview Question
Some Real-time scenarios where you can use the Singleton Design Pattern:
Service Proxies: As we know invoking a Service API is an extensive operation in an application. The process that taking most of the time is creating the Service client in order to invoke the service API. If you create the Service proxy as Singleton then it will improve the performance of your application.
Facades: You can also create Database connections as Singleton which can improve the performance of the application.
Logs: In an application, performing the I/O operation on a file is an expensive operation. If you create your Logger as Singleton then it will improve the performance of the I/O operation.
Data sharing: If you have any constant values or configuration values then you can keep these values in Singleton So that these can be read by other components of the application.
Caching: As we know fetching the data from a database is a time-consuming process. In your application, you can cache the master and configuration in memory which will avoid the DB calls. In such situations, the Singleton class can be used to handle the caching with thread synchronization in an efficient manner which drastically improves the performance of the application.
What is the Singleton pattern in Java?
Singleton pattern in Java is a pattern that allows only one instance of Singleton class available in the whole application. java.lang.Runtime is a good example of a Singleton pattern in Java.