Demystifying Singleton Design Pattern in Java

Design pattern is a solution at the design level for recurrent problems that we software engineers experience frequently. This article addresses the Singleton Pattern, which many consider to be the most basic but is still one of the most commonly used design patterns.

Susith Hemathilaka
4 min readApr 8, 2021
Image Courtesy: Ricardo on Unsplash

Types of Design Patterns

There are 23 design patterns in total. They are classified into three categories.

  1. Creational Design Patterns- These patterns designed for class instantiation with class-creation patterns or object-creational patterns.
  2. Structural Design Patterns- These patterns deal with class structure and object composition. main objective is to increase the functionality of the classes while keeping it’s structure efficient and flexible.
  3. Behavioral Design Patterns- These patterns are designed with regard to Object communication and how they interact with each other.

Singleton Design Pattern

Singleton design pattern is a creational design pattern and it focus on creation of objects. singleton pattern used to ensure only one instance can be created from a class. Cool! ✌.

Where we use Singleton?

To ensure only one instance created to provide global point of access to the resource costly objects. In terms of practical singleton patterns are used when connecting to external resource such as database through DB driver or DB Manager, logger, application configurations and caching.

Moreover singleton design pattern is building block of many other design patterns like factory, builder, prototype, facade and etc.

Implementing Singleton

we will look at few thing before implement singleton class. There are Common components in Singleton class.

A class using the singleton design pattern will include,

Singleton Class Diagram

private constructor- to avoid others classes from creating new instances.

private static variable- to store the constructed instance.

public static method- to return the class instance we stored in private static variable.

All right, let’s gets dirty our hands with coding. There is more than one ways to implement singleton design pattern. We will discuss about only 3 mostly used implementation according to the different scenarios.

Eager Initialization

Eager initialization is the easiest way to create a singleton class. In eager initialization, the instance of singleton created at the time of class loading. Simply, It make a instance before getting request to initialize from other class. Then it leads to a drawback that instance is created even though client application might not be using it.

Lazy Initialization

Lazy initialization only create instance when some other class request for instance. The only instantiated static variable is initially declared null, and it is only instantiated when null at the time of the check.

getInstance() method will check if there is any instance of that class is already created. If yes, then our method getInstance() will return that old instance and if not then it creates a new instance of the singleton class in JVM and returns that instance.

Dealing with multi threaded environments

Singletons created using eager or lazy initialization are not thread safe. Then we need to write thread safe code when dealing with multi threaded programs.

Where the problem occurs?

If both the threads calls out getInstance() method at the same time, the instance == null condition will return for both the thread. So, two different instances of the same class will be created. That will break the singleton principle.

Synchronized block can be used to ensure singleton works fine and only one instance created to share between many threads. It avoids two or more threads try to create objects in same time. Let’s look how we can make thread safe singleton.

Enhance Performance

Now code is totally safe right! But performance is critical aspect whilst writing safe code. if we synchronized in above way threads will acquires lock everytime when it try to get instance. Our next effort is reduce the count of acquring lock and enchance performance. For that we use double check lock singleton pattern. In here it acquire lock only when instance is null wchich means first and only time creating the singleton instance. Let’s move to it.

Wrapping Things Up

Finally, hope you got an clear idea of singleton principle and its’ uses. This article attempts to consolidate most of the common designs approaches of singleton. Although singleton is criticized for associated drawbacks too. To make perfect singleton based on the scenario you can use more advanced techniques.

If there is anything that I have mentioned incorrectly, feel free to comment down below!. If you liked the post, click the 👏 below so more people can see it! Make sure that you follow me on Medium or on My Blog to get update whenever new article gets published.

Happy Coding!👌

--

--

Susith Hemathilaka

An avid developer with an unquenchable thirst for anything in programming ✌ University of Westminster • Software Engineer @ DirectFN