In this code fragment, there is a
ChocolateBoiler which has a
- static final method getInstance and
- a static instance variable boiler.
The default constructor of the ChocolateBoiler class is marked as private.
The constructor of this class cannot be called from an outer class because it is private. This prevents the instantiation of the class from an outer class.
Hence, only a static method inside the class can access the constructor of the class.
The getInstance method serves this purpose and when the getInstance method is invoked, it checks for the boiler variable to be null.
If yes, it instantiates the boiler variable, else it returns the object which is already referenced by the boiler variable.
Hence, it is verified that there is one and only one object
that is created and returned when asked for.
This type of design pattern is called the Singleton design pattern in Java.
However, when multithreading
comes into the picture, if two or more threads somehow enter the "if block" in the getInstance method,
there will be two instances of the ChocolateBoiler which is contradictory to the Singleton pattern.
So marking the getInstance method as synchronized
ensures thread safety because only one thread will be able to enter the method at a time.