Also known as Early Instantiation.In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.
If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections, etc. We should avoid the instantiation until unless client calls the getInstance method. Also, this method doesn’t provide any options for exception handling.
public class SingletonClass { | |
private static volatile SingletonClass slt = new SingletonClass(); | |
//private constructor. | |
private SingletonClass(){} | |
public static SingletonClass getInstance() { | |
return slt; | |
} | |
} |
Lazy Initialization:
public class SingletonClass { | |
private static SingletonClass slt; | |
private SingletonClass(){} //private constructor. | |
public static SingletonClass getInstance(){ | |
if (slt== null){ //if there is no instance available.create new one | |
slt= new SingletonClass(); | |
} | |
return slt; | |
} | |
} |
*************************************************
API Testing Interview Question Set:
https://automationreinvented.blogspot.com/search/label/Rest-API
Kubernetes Interview Question Set
https://automationreinvented.blogspot.com/search/label/Kubernetes
Docker Interview Question Set
https://automationreinvented.blogspot.com/2020/02/top-18-docker-commands-for-aytomation.html
Linux Interview question Set
https://automationreinvented.blogspot.com/search/label/Linux
Automation Testing/SDET Framework Design
https://automationreinvented.blogspot.com/search/label/FrameworkDesign
Java Related Interview Question Set
https://automationreinvented.blogspot.com/search/label/Java
GIT Interview Question Set:
https://automationreinvented.blogspot.com/search/label/GIT
Coding Interview Question Set:
https://automationreinvented.blogspot.com/search/label/Coding%20Questions