Java — Singleton Design Pattern Example | Code Factory

Donate : Link

WordPress Blog : Link

Singleton design pattern is used when you want to have only one instance of a given class.

It is a creational design pattern wherein we deal with the creation of objects.

In object-oriented design, It’s very important for some classes to have only one instance. That’s because they represent something unique, something that’s one of its kind.

How do you ensure that a class has only one instance? Well, there are several ways of doing this in Java. But all of them are based on the following basic ideas:

  1. Declare a private constructor to prevent others from instantiating the class.
  2. Create the instance of the class either during class loading in a static field/block, or on-demand in a static method that first checks whether the instance exists or not and creates a new one only if it doesn’t exist.

Let’s see all the possible solutions with code samples one by one :

1. Eagerly Initialized Singleton

package com.example.java.programming.singleton;

The disadvantage of this approach is that the instance is created irrespective of whether it is accessed or not. This is fine if the object is simple and does not hold any system resources. But can have performance implications if it allocates a large amount of system resources and remains unused.

2. Eagerly Initialized Static Block Singleton

You can also create the one-off instance of the class in a static block. This works because the static block is executed only once at the time of class loading.

The advantage with static block initialization is that you can write your initialization logic or handle exceptions in the static block.

package com.example.java.programming.singleton;

Just like the previous solution, the instance is created whether or not it is needed by the application.

3. Lazily Initialized Singleton

Lazy initialization means delaying the initialization of something until the first time it is needed.

In the following implementation, we first check whether the instance is already created or not in the getInstance() method. If the instance is already created, we simply return it, otherwise, we first create the instance and then return it:

package com.example.java.programming.singleton;

Notice the use of synchronized keyword in the getInstance() method. This is needed to prevent race conditions in multi-threaded environments.

Let’s say that the instance is not created yet, and two threads enter the getInstance() method simultaneously. In that case, the instance==null check will evaluate to true and both the threads will create a new instance of the class.

The synchronized keyword ensures that only one thread can execute the getInstance() method at a time.

4. Lazily Initialized Double-Checked Locking Singleton

The synchronized keyword added to the getInstance() method prevents race conditions, but it also incurs some performance penalty.

Following is an optimized version of the lazily initialized singleton where — instead of making the entire method synchronized, we create a synchronized block and wrap only the instantiation part inside the synchronized block

package com.example.java.programming.singleton;

The above approach is called Double-Checked Locking because we double-check whether the variable is initialized or not inside the synchronized block.

The double-checking is very important here. Let’s say that two threads T1 and T2 enter the getInstance() method simultaneously. The instance==null check will evaluate to true, so both of them will enter the synchronized block one-by-one. If the double check was not there, both threads would create a new instance.

Also, notice the use of volatile keyword with the instance variable. This is necessary to prevent compilers from doing their own optimizations and handle the singleton correctly.

5. Lazily Initialized Inner Class Singleton (Bill Pugh singleton)

Bill Pugh came up with a very efficient solution to create singletons. It is called Initialization-on-demand holder idiom. In this approach, a static inner class is used to lazily create a singleton instance.

package com.example.java.programming.singleton;

Note that, the inner class is not loaded until the getInstance() method is invoked for the first time. This solution is thread-safe and doesn’t require any synchronization. It is the most efficient approach among all the singleton design pattern implementations.

6. Enum Singleton

An Enum is singleton by design. All the enum values are initialized only once at the time of class loading.

package com.example.java.programming.singleton;

Output :

Initializing enum with [Monday, Tuesday, Wednesday, Thursday, Friday]
Initializing enum with [Saturday, Sunday]
EnumSingleton{days=[Monday, Tuesday, Wednesday, Thursday, Friday]}
EnumSingleton{days=[Saturday, Sunday]}

The disadvantage of this approach is that it is a bit inflexible compared to other approaches.

Singletons and Reflection

Java’s Reflection API is very powerful. You can use Reflection to instantiate a class even if the class’s constructor is private.

package com.example.java.programming.singleton;

Output :

singletonInstance hashCode: 366712642
reflectionInstance hashCode: 1829164700

Notice how we created a new instance of the Singleton using constructor.newInstance(). This destroys the singleton pattern.

Protection against Reflection

To protect your singleton class against instantiation via reflection, you can throw an exception from the private constructor if the instance is already created like this

class MySingleton {
private static final MySingleton instance = new MySingleton();

You can also use an Enum singleton to guard against reflection. Enums can’t be initialized via reflection. They are a sure shot way of having a single instance no matter what.

Singletons and Serialization

We often need to serialize/deserialize objects in Java. Any class that needs to be serialized/deserialized must implement the serializable interface.

Note that, the de-serialization step always creates a new instance of the class, which destroys the singleton pattern. Here is an example

package com.example.java.programming.singleton;

Output :

instance1 hashCode: 865113938
instance2 hashCode: 1283928880

Notice how the hashCodes of the original instance and the de-serialized instance are different. There are clearly two instances of our singleton class.

Protection against Serialization

To prevent the de-serialization process from creating a new instance, you can implement the readResolve() method in the singleton class. It is invoked when the object is de-serialized.

In the readResolve() method, you must return the existing instance -

package com.example.java.programming.singleton;

Output :

instance1 hashCode: 865113938
instance2 hashCode: 865113938