Let’s Learn Singleton Design Pattern

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.

 

singleton pattern overview
singleton pattern overview

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 sequence
singleton pattern sequence diagram

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

Singleton Class
Singleton Class Structure

 

  • 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,

  1. Add the class definition
  2. Add static field in order to ensure it will be the one and only instance for whole applications and initialize it to null

  1. Make the constructor private to avoid future class instantiations through other classes
  2. 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. Use the singleton object by calling the getInstance() method

Basic Implementation of a Singleton Class

 

Singleton class template
Singleton class template

Other Implementation Approaches

The following section will briefly show how the singleton pattern can be implemented in different ways. List of different implementations are,

  1. Lazy initialization
  2. Eager Initialization
  3. Static block initialization
  4. Thread Safe Singleton
  5. Bill Pugh Singleton Implementation
  6. 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.

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.

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.

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.

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.

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

Enum Singleton

Enums can also be used to create singletons. Here is the example of an Enum Singleton.

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

  1. Reflection
  2. Serialization
  3. Cloning

Reflection can break Singleton Pattern

Let’s see the example code that can break the Singleton Pattern

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

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.

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.

 

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.

 

5 thoughts to “Let’s Learn Singleton Design Pattern”

  1. 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?

Leave a Reply