What is a Singleton?
The word singleton is derived from the word, Single which represents one independently executable unit. In the programming world, a singleton is an object which has only one instance for the life time of the application.
What is Singleton Design Pattern?
Singleton design pattern is classified as a creational design pattern because it provides a solution to overcome repeatable instantiation of a unique object in the system. Singleton design pattern ensures a particular class has only one object instance for the lifetime of an application. That object is accessible via a global point of access and it is shared among all the required resources.

Participants
Singleton Class: Provides the access for its unique instance for the clients
Client: Accesses a singleton solely via singleton’s instance() method
Sequence Diagram
Below is a simple sequence diagram to explain the process of singleton design pattern.

Singleton Pattern Usage in Software World
It’s possible to identify the use of singleton pattern with any system. Utility programs inside an operating system heavily use the singleton pattern to simplify its complex situations. Logging, caching, registry settings, external resources like printers, device drivers, databases are some of the examples.
In more familiar way, let’s think of the ‘Find’ function in a Microsoft Word document. Clicking ‘Ctrl + F’ will give you the ‘Find and Replace’ dialog box and you just have to apply the required phrase. If you click ‘Ctrl + F’ hundred times while the first one is opened you won’t get 100 dialog boxes. There will be only one opened ‘Find and Replace’ dialog box per one opened word document at a time. Things will get far complicated if we get multiple dialog boxes per our clicks. Here ‘Find and Replace’ is the single shared instance and ‘Ctrl + F’ acts as the point of access in the simple explanation. Likewise, MS Words ‘Find’ function uses a singleton to achieve its objective.
Additionally, we can find singleton design pattern usage in core java classes like ‘java.lang.Runtime’ and ‘java.awt.Desktop’.
Real World Example
Let’s think about the notice board in a school, office staff update any messages related to school events on the notice board time to time. Students and Teachers use this notice board to get updates on those messages frequently. Only the messages added and deleted but the notice board remains same. Likewise, only the state and use of the object is changed but the singleton object instance remains same.
What is the purpose of the Singleton Design Pattern?
The main purpose of the singleton design pattern is to restrict the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. More specifically it limits the number of objects to only one. If multiple objects are expecting the service of the singleton class, all those objects will share the same singleton class instance.
Problem Statement for the Singleton Design Pattern
The application needs one and only one instance of the object with a global point of access and sharing ability.
What is a Singleton Class?
Singleton class is a class that should create only one instance per an application or java virtual machine. It shouldn’t allow the creation of multiple objects with different statuses. If try to instantiate separately, the new variable should points to the first instance created. Any further modifications from anywhere will be affected to the single instance and will change the state and that changes will be visible to next client who uses that object.
To be a Singleton Class,
- It should limit the number of object instantiation to one
- Provide a global point of access to reach the singleton instance
Structure of the Singleton Class

- Instance: This is a static field to hold the instance of the singleton class
- Private Constructor: Constructor is private so that nobody else can instantiate it again
- Static Public Method: This method is the global point of access to the static singleton object and this method returns the instance to the caller
Where can we find Singletons?
You can easily find that singletons are used to control resources like database connections, sockets and registries. Logging mechanism of the system also a popular use of singleton pattern, which provides a single access point to manage the application log file. Configuration File also acts as a singleton. Any change at any point only inserted via this single configuration file
What is the difference of Singleton Class?
To instantiate a normal java class we use the class constructor with the new key word, but to instantiate a singleton class we just have to call getInstance() static public method.
How to Implement a Singleton Class?
Though singleton design pattern is known as one of the simplest patterns in the list, it can be a bit complex when deciding the best implementation method. There are several implementation approaches to achieve the singleton-ness depending on the requirements and conditions of the system.
Basic Steps to Implement a Singleton Class
Even though there are several specific methods to implement singleton pattern, all those follow the same concept as below,
- Add the class definition
- Add static field in order to ensure it will be the one and only instance for whole applications and initialize it to null
1 |
private static Runtime runTime = null; |
- Make the constructor private to avoid future class instantiations through other classes
- Add getInstance() method – This is the global access point of the singleton instance, the method should be static, accept no parameters and return the object of the class type. Unless the instance is null, there is no need to use the new operator to create the object
1 2 3 4 5 6 7 8 9 |
public static synchronized Runtime getInstance(){ if(logger == null) logger = new Runtime (); return runTime; } |
- Use the singleton object by calling the getInstance() method
1 2 3 4 5 6 7 |
Runtime runTime1 = Runtime.getInstance(); Runtime runTime2 = Runtime.getInstance(); runTime1.logDeposit(“0001”, 80.5); runTime2.logWithdraw(“0002”, 100); |
Basic Implementation of a Singleton Class

Other Implementation Approaches
The following section will briefly show how the singleton pattern can be implemented in different ways. List of different implementations are,
- Lazy initialization
- Eager Initialization
- Static block initialization
- Thread Safe Singleton
- Bill Pugh Singleton Implementation
- Enum Singleton
Lazy initialization
As the name suggests this approach will instantiate the singleton instance lazily. Below code contains the private static member ‘lazyIntance’ which will be get instantiated only the application cannot find a previously instantiated object. Inside the getInstance() method, it checks whether the singleton object reference is null it will proceed with the new object. There will be issues in multi-threaded systems due to several threads accessing the ‘lazyInstance’ at the same time within the ‘If’ block yielding different instances to the same singleton class which destroys the concept of the singleton.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class MyLazySingleton { private static MyLazySingleton lazyInstance; . private MyLazySingleton (){} public static MyLazySingleton getInstance(){ if(lazyInstance == null){ lazyInstance = new MyLazySingleton (); } return lazyInstance; } } |
Eager Initialization
Opposite to lazy initialization, eager initialization creates the new singleton object at the time of class loading. Observe the static member declaration, it is ended with the new operator which will always yield a new object to the pool. The getInstance() method will yield that previously created object for client calls without much effort. The main issue of this approach is the performance overload due to unnecessary object creation. Also, there is no room for exception handling as well, making the system more unpredictable and error-prone.
1 2 3 4 5 6 7 8 9 10 |
public class MyEagerSingleton { private static final MyEagerSingleton eagerInstance = new MyEagerSingleton (); private MyEagerSingleton (){} public static MyEagerSingleton getInstance(){ return eagerInstance; } } |
Static Block Initialization
This approach can be identified as an improvement to the eager initialization approach. Here, the singleton instance will be initialized within a special static block which also have the exception handling facility upon object creation. Since the static blocks will be executed only once object will be created only once for the lifetime of the application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class MyStaticBlockSingleton{ private static MyStaticBlockSingleton staticInstance ; private MyStaticBlockSingleton (){ } static { try{ staticInstance =new MyStaticBlockSingleton (); } catch(Exception e){ throw new RuntimeException("Exception in static block"); } } public static MyStaticBlockSingleton getInstance(){ return staticInstance; } } |
Thread Safe Singleton
In this approach, a singleton object is created within a synchronized code block. Also, it’s on its lazy loading mechanism where the object gets instantiated within the getInstance() static method only if any prior instantiated object was absent in the system. Unfortunately, this approach will cause performance issues due to locking overhead with the synchronized method and with the time synchronization might get redundant since the system can use the already created object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class MyThreadSafeSingleton { private static MyThreadSafeSingleton threadSafeInstance; private MyThreadSafeSingleton (){} public static synchronized MyThreadSafeSingleton getInstance(){ if(threadSafeInstance == null){ threadSafeInstance = new MyThreadSafeSingleton (); } return threadSafeInstance; } } |
Above drawback can be eliminated using Double Checked Locking mechanism. The modification is to include the synchronization code inside an ‘If’ condition which checked for the availability of a previous instance. So that the system doesn’t need to proceed with the locking mechanism which causes the performance issues.
1 2 3 4 5 6 7 8 9 10 11 |
……………………. public static MyThreadSafeSingleton getInstanceUsingDoubleLocking(){ if(threadSafeInstance == null){ synchronized (MyThreadSafeSingleton.class) { if(threadSafeInstance == null){ threadSafeInstance = new MyThreadSafeSingleton (); } } } return threadSafeInstance; } |
Bill Pugh Singleton Implementation
Creating a Singleton using an inner class. The inner class holds the static instance of the outer class and hence the instance is not instantaited when the class is loaded first time. This is also a type of Lazy Initialization
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class BillPughSingleton { // instantiation not allowed outside this class private BillPughSingleton() { } private static class SingletonHolder { private static final BillPughSingleton INSTANCE = new BillPughSingleton(); } public static BillPughSingleton getInstance() { return SingletonHolder.INSTANCE; } } |
Enum Singleton
Enums can also be used to create singletons. Here is the example of an Enum Singleton.
1 2 3 |
public enum EasyEnumSingleton{ INSTANCE; } |
The initialization of singleton is guaranteed by Java. The developer doesn’t need to worried about the thread safety, the serialization issue(discussed next) or the cloning issue. But enums instance are loaded into memory as soon as the enum is loaded and hence the lazy initialization is not possible.
Challenges of Singleton Pattern
- Reflection
- Serialization
- Cloning
Reflection can break Singleton Pattern
Let’s see the example code that can break the Singleton Pattern
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class SingletionBreaker { public static void main(String[] args) { BillPughSingleton expectedSingleton = BillPughSingleton.getInstance(); BillPughSingleton reflectionInstance = null; try { Constructor<?>[] singletonClassConstructors = BillPughSingleton.class.getDeclaredConstructors(); for (Constructor<?> each : singletonClassConstructors) { // take apart the singleton each.setAccessible(true); reflectionInstance = (BillPughSingleton) each.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } System.out.println("BillPughSingleton1.hashCode():- " + expectedSingleton.hashCode()); System.out.println("BillPughSingleton2.hashCode():- " + reflectionInstance.hashCode()); } } |
The output of this example above is two hashcodes. Reflection is used widely in libraries and hence can break some singletons that are distributed to outside world. For this reason, Joshua Block suggested the Enum Singleton pattern that we have discussed above.
Serialization
If a singleton class is serialized and deserialzed, the singleton pattern is broken as shown in below example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class SerializerBreaker { public static void main(String[] args) { try { BillPughSingleton BillPughSingletonInstance = BillPughSingleton.getInstance(); ObjectOutput out = new ObjectOutputStream(new FileOutputStream("BillPughSingleton.txt")); out.writeObject(BillPughSingletonInstance); out.close(); ObjectInput in = new ObjectInputStream(new FileInputStream("BillPughSingleton.txt")); BillPughSingleton deSerializedInstance = (BillPughSingleton) in.readObject(); in.close(); System.out.println("BillPughSingleton1 hashCode:- " + BillPughSingletonInstance.hashCode()); System.out.println("BillPughSingleton2 hashCode:- " + deSerializedInstance.hashCode()); } catch (Exception e) { e.printStackTrace(); } } } |
The output is two different hashcodes. So as to fix the issue with the Serialization, the Singleton class needs to implement the following method. And the method needs to return the singleton instance.
1 2 3 4 |
protected Object readResolve() { return INSTANCE; } |
Cloning
Cloning can be used to copy an object. Cloning can also be a challenge for the Singleton pattern. And the fix for cloning is a simple one, The Singleton Object should not allow cloning.
1 2 3 4 |
@Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } |
Uses of Singleton Design Pattern?
- To avoid incorrect program behavior
- Eliminate resource overuse or inconsistencies
- When it’s not safer to have more than one instance of a class
- To handle situations where you don’t want to repeat object creation
- If the object in question is not expected to change
- When using stateless classes like validators, instead of using static methods for validation singleton instance can support the mocking the instance itself.
Consequences & Limitations
- Unique instance is under strict control on when and how the clients access it
- Single instance creation and usage are far complicated when working with complex systems.
- Sometimes several threads fight to access the singleton instance creating performance issues.
- They cause tightly coupled code with the global variable usage and introduces unwanted dependencies
Singleton Class Vs. Static Class
- Unit testing is far easier when using the singleton class. Because mocked or stubbed version of the singleton class can be used as parameter to any setter method or constructor
- Singleton can extend other classes and implement interfaces while static class cannot
- Singleton can select upon whether to initialize lazily or asynchronously while static class will generally initialize at its first load
- Singleton class can have constructors for different
- We can dispose the objects of a singleton class but not of static class.
All in all, even though singleton pattern is known as one of the simplest patterns on the list, it better to know the various implementation approaches and pros and cons when considering the applicability of this pattern to your system. A good use of singleton pattern will always yield best performance and efficiency in your code.
Well written. Please also share factory method pattern
Very well written.
Super. Thank you
Very well explained. Being a student of computer science, understanding design patterns is essential. Please share other patterns also. Can we use these patterns in other languages and not only java?
Patterns are used in every language. Read Introduction to design patterns
Yes. Design patterns are not language specific. For example same can be implemented in golang. Refer this:
Very well explained. Thank you. For Singleton pattern in golang, I found this article also useful:
Simple and easy to understand.