Java Singleton is most important feature to understand.
Singleton is a design pattern where a class can have only one instance per application.
Logging, driver objects, caching, etc. are some of the examples of Singleton design pattern.
Singleton class will follow below three rules most of the time:
Note: Singleton class will always return same instance of class.
There are two ways to create singleton instance:
Eager loading is to create an instance at the time of class load.
Lazy loading is to create an instance at the time when it is required.
Follow below inline steps to create eager loading singleton class instance.
OUTPUT
true
Output is true as this class is singleton and will always return same instance.
Follow below inline 4 steps to create lazy loading singleton class instance.
OUTPUT
true
Output is true as this class is singleton and will always return same instance.
In case of thread safe singleton class, only one thread can access singleton class instance at the same time.
Addition of synchronized keyword in static getInstance() method will convert above lazy loading singleton class to Synchronize or thread safe singleton class as shown below highlighted red in color.
OUTPUT
true
Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.
📝 Blogs
javadoubts.com © All rights reserved