Java Program to Demonstrate the Nested Initialization For Singleton Class
A Singleton Class is capable of producing just a single instance. Every Singleton class has a getInstance method which returns its object. When the getInstance method is called for the first time, an object of the class is generated, stored, and then returned. On subsequent calls to getInstance, the same object generated earlier gets returned.
Nested Initialization can be used for making Singleton classes.
In the below implementation we are creating a Singleton class using Nested Initialization. Make the following observations:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- The default no-arg constructor of this class is made private to prevent other classes from directly accessing it and making objects of Singleton.
- The Singleton class has a static public getInstance method with Singleton as the return type. This will be used by other classes to get the object of Singleton.
- There is a Nested class inside Singleton class. This Nested class has an Instance variable that stores the object of the Singleton class.
- The getInstance method takes value from this Instance variable and returns it to the call site.
Demonstration of the creation of a Singleton class using Nested Initialization
Object made geeksforgeeks!
Advantages of Nested Initialization:
- Lazy loading
- Lazy loading is simply postponing the object creation until it is actually needed.
- It results in increased performance as the overhead during program startup is reduced.
- In our case, the object of the Singleton class is not created until the getInstance method is called for the first time.
Thread-Safety: Thread-Safety is essential, else multi-threaded programs can yield unexpected random results.
- A non Thread-Safe implementation of Singleton class
Object made Object made
- The Nested Initialization is thread-safe, this is because unlike the above implementation in Nested Initialization the getInstance method does not create an object, it simply returns it. The object is created when the Nested Class is initialized and this happens only once when the getInstance method is called for the very first time.
Thread-Safe implementation of Singleton class
Note: In the above implementation we have achieved thread-safety without using the synchronized keyword. This is a plus point since the synchronized keyword is known to affect performance noticeably.