Sun of our solar system is an excellent example of the singleton pattern. All the planets in our solar system have one sun and it has a global point of acess.
What is it?
Singleton is a creational design pattern that lets you ensure that a class has
only one instance and the instance has a global access point
The singleton design pattern solves problems like:
- How can it be ensured that a class has only one instance?
- How can the sole instance of a class be accessed easily?
- How can a class control its instantiation?
- How can the number of instances of a class be restricted?
All implementations of the Singleton have these steps in common:
- Make default constructor private to control class instantiation
- Create a static creation method that underhood the hood uses the private constructor to create an instance then stores it in a static field and all subsequent calls to this method return cached object
The above code will work for single threaded applications . But there's a potential that multiple objects get created in a multithreading environment. Here's one example scenario:
- Thread A calls the method getInstance and finds the onlyInstance to be null but before it can actually new-up the instance it gets context switched out.
- Now thread B comes along and calls the getInstance method and goes on to new-up the instance and returns the Sun object.
- When thread A is scheduled again, is when the mischief begins. The thread was already past the if null condition check and will proceed to new-up another object of Sun and assign it to onlyInstance. Now there are two different Sun objects out in the wild, one with thread A and one with thread B
There are two trivial ways to fix this race condition:
One is to add synchronized to the getInstance() method.
- synchronized public static AirforceOne getInstance()
The other is to undertake static initialization of the instance, which is guaranteed to be thread-safe.
- private static AirforceOne onlyInstance = new AirforceOne();
- A class has only a single instance.
- You gain a global access point to that instance.
- The singleton object is initialized only first time.
- Violates the Single Responsibility Principle.
- The pattern requires special treatment in a multithreaded environment so that multiple threads won’t create a singleton object several times.
- Difficult to unit test
Github Code Repository:
The code for the Singleton pattern can be found at following github repository:
Github repository link: Singleton pattern