What is a singleton pattern?
Singleton pattern is used in cases where we want to ensure that only a single instance of the class exists in the application. It is one of the most popular patterns. With lot of views around the web calling it a code smell.
In this post I will not be getting into discussing whether singleton pattern is good or bad, but will only show how can we implement a singleton pattern in Java.
Java Implementation
class Singleton { | |
private static Singleton instance = null; | |
private Singleton(){} | |
public static Singleton getInstance(){ | |
if (instance == null) { | |
instance = new Singleton(); | |
} | |
return instance; | |
} | |
} |
The above snippet shows how you can write a class such that only a single instance of this class can be created. But what happens when we have more than one thread executing concurrently. What if they reach the null check at the same time.
Well, we will have more than one instance of the Singleton class. Thus the above mechanism of creating a singleton class is not effective.
Let us try to make this thread safe.
We added the synchronized keyword to the method. This makes the instance creation thread safe. However, it adds unnecessary wait times for all the threads, even when the instance creation has already been done.
Let us try to optimize further.
We do a null check, if the instance is already initialized, no thread will block. Incase the initialization is yet to happen, one of the threads will try to get the lock on the object and initialize the instance.
The second null check is to avoid duplicate instance being created, incase two threads reached the null check at the same time.
This is how you can create a singleton class that is thread safe.
References:
https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons
https://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
4 thoughts on “Singleton Pattern – Implementation in Java”
Comments are closed.