Singleton Design Pattern
Singleton design pattern falls under creational design pattern category which restricts a class to have only one instance and provide global access.
Singleton design pattern is a famous design pattern and often asked in interviews. It is very simple and has a lot of use cases involving object reuse like Database Connections. Instead of instantiating a database connection everytime one needs to run a database query, one can create a singleton database connection and reuse the same database object for executing queries.
In this article, let's explore various different ways for creating a singleton and their code implementations in Java.
There are four ways, I am going to discuss to create a singleton.
- Eager Initialization
- Eager Initialization with exception handling
- Lazy Initialization with synchronized keyword.
- Lazy Initialization and threadsafe without using synchronized keyword.
Eager Initialization
Here, we are going to use public static final field and initialize the object. The static fields gets initialized only once i.e when the class is loaded.
It is a variable which belongs to the class and not to object(instance). Static variables are initialized only once, at the start of the execution.
A single copy to be shared by all instances of the class. A static variable can be accessed directly by the class name and doesn’t need any object.
Eager Initialization with exception handling
A disadvantage of above initialization is there is no exception handling. If we are supposed to read a configs file, if the file doesn't exist it will throw an IO Exception. There is no Exception handling if we initialize the object in the above manner.
A neat approach is to initialize in a static block as static blocks gets executed before static variables.
Lazy Initialization
Above code is an lazy initialization example in java where an object is initialized only when getInstance() method is called upon.
However, the above code is not thread safe. When both threads simultaneously tries to call the getInstance() method, each thread may end up with creating a separate instance each.
How to make it thread safe?
Using synchronized key word. We can use synchronized keyword over method to restrict only one thread entering the if block and initializing the object. However, this is a bit slower if even after initializing the object, second thread has to wait until the first thread exits.
This can be made faster by using synchronized block like in getInstanceViaDoubleCheckLocking(String value) method below.
Lazy Initialization and threadsafe without using synchronized keyword.
Keep Experimenting 🔎
Keep Learning 🚀
Post a Comment