Pages

Wednesday, 9 October 2019

What is Eager and Lazy Initialization of Singleton Class ? Interview questions for Automation Testing/Core Java



Eager Initialization:

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:

In such case, we create the instance of the class in synchronized method or synchronized block, so instance of the class is created when required.Opposite to Eager initialization, here we are going to initialize new instance of the class in getInstance() method it self. This method will check if there is any instance of that class is already created? If yes, then our method (getInstance()) will return that old instance and if not then it creates a new instance of the singleton class in JVM and returns that instance. This approach is called as 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;

}

}


Note : To make the singleton class thread safe we need to make getInstance() Synchronized 
 

*************************************************

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
 

No comments:

Post a Comment