Tuesday 13 March 2018

SINGLETON Design Pattern: Ways of Implementation

As name says, at any time only one instance of a Singleton class must be present. All classes accessing the singleton class must use the same instance.

To make a class Singleton:

The constructor must be private, so no external class can create an instance using direct constructor.
So are we suppose to create an instance of this class ?

One way to get the instance of the Singleton class is by having a static final object of the class.
public static final MySingleton mInstance = new MySingleton ();

This is called early initialization as the singleton object is initialized when the class is loaded.
The singleton object can be created when actually required, to same resources, as shown below.

This is called lazy initialization. The object instance is initialized only when required.

The above snippet works fine as long as multiple threads don’t call the getInstance() method, though we can not control which thread calls the method.The real problem starts when multiple threads request the instance. The above snippet will lead to Multiple Instances being created if called by multiple threads at the same time.

To fix this problem, we can synchronize the getInstance() method

But the above approach has performance issues. The time required to finish the getInstance() method increases due to synchronization. And moreover, once the instance is created, synchronization would be of no use, as the already created object can be returned directly. The Object instance will internally handle the synchronization within itself when the object is accessed in different threads.

So only the critical object creation part of code needs to be synchronized, as shown below.

Above code snippet reduces the getInstance() method access time, since it synchronizes only while creating the object. Once the object is created, it is returned to the caller, without any synchronization.

But the above code can also lead to multiple instances of the Singleton class. If two threads are waiting at the “synchronized (BetterSingleton.class)” line, each will create its own instance of the object and return.

To solve this, we use “double-checked-locking“.

Using double checked locking ensures the Singleton nature of the class.


Post a Comment


Get in touch with me


Bangalore, India