×

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary. When the cost of constructing an object is high, or the item is rarely used by the program, lazy loading is crucial. A method for increasing program efficiency is lazy loading. We will go into more detail about lazy loading in this section.

Initializing a class only when it is truly required is known as "lazy loading," which is just a fancy word for the procedure.

In order to maintain ease of use and boost efficiency, lazy loading is a software design style where object initialization only takes place when it is truly required and not before.

When the cost of creating an item is very expensive, and its use is quite uncommon, lazy loading is crucial. Therefore, this situation justifies the implementation of lazy loading. Loading objects and data only when necessary is the core concept of lazy loading.

Assume, for instance, that you are developing an application with a ContctList object that holds a list of the firm's employees and an organization object that represents the company. A corporation may have thousands of employees. It could take a long time to load the ContctList object, the Company object, and the ContctList object's list of all the company's employees from the database. Even when you don't need the personnel list, you often have to wait until the company's information is loaded into the RAM.

Employing the Lazy Loading Design Pattern, it is possible to delay loading employee objects until they are needed, which can save both time and memory.

Implementation of Lazy loading:

Virtual Proxy:

Virtual Proxy is a memory-saving technique that encourages delaying the creation of objects. Take note of the program below.

LazyLoadExample.java

// demonstrating Lazy Loading in Java (virtual Proxy)   
  
// import statements  
import java.io.*;
import java.util.ArrayList;  
import java.util.List;  
  
// declaring the interfaces 
interface IcontctList  
{  
public List<Employees> getEmploList ();  
}  
  
class Company  
{  
// fields or variables or attributes of the compny class 
String cNam;   
String cAdd;  
String cContctNo;  
IcontctList contList;  
  
// constructor helpful in initializing the class variables and fields
public Company (String cNam, String cAdd, String cContctNo, IcontctList contList)  
{  
this.cNam = cNam;  
this.cAdd = cAdd;  
this.cContctNo = cContctNo;  
this.contList = contList;  
}  
  
// a get method to retrieve the name of compny  
public String getCompanyName ()  
{  
return this.cNam;  
}  
  
// a get method to retrieve the address of compny 
public String getCompanyAddress ()  
{  
return this.cAdd;  
}  
public String getCompanyContactNo ()  
{  
return this.cContctNo;  
}  
  
// a get method to get the contct list 
public IcontctList getcontList ()  
{  
return this.contList;  
}  
  
}  
  
class ContactList implements IcontctList   
{  
// retrieving the list  
@Override  
public List<Employees> getEmploList()  
{  
return getEmpList();  
}  
private static List<Employees> getEmpList ()  
{  
List<Employees> empList = new ArrayList<Employees> (5);  
  
// adding employees to list  
empList.add (new Employees ("Mohan", 3452.67, "SDE3"));  
empList.add (new Employees ("Ajay", 22745, "ASE"));  
empList.add (new Employees ("Nani", 3266.17, "G4"));  
empList.add (new Employees ("Virat", 4795.34, "SDE1"));  
empList.add (new Employees ("Akhila", 2657.87, "SDE"));  
  
return empList;  
}  
}  
  
class ContactListProxy implements IcontctList   
{  
  
private IcontctList contList;  
  
@Override  
public List<Employees> getEmploList ()  
{  
if (contList == null)   
{  
System.out.println ("printing the list of employees ... \n");  
contList = new ContactList ();  
}  

return contList.getEmploList ();  
}  
}  
  
class Employees  
{  
// Attributes of the employee's class  
private String empNam;  
  
private double empSal;  
private String empDes;  
  
// constructor  initializing the class attributes/fields   
public Employees (String empNam, double empSal, String empDes)  
{  
this.empNam = empNam;  
this.empSal = empSal;  
this.empDes = empDes;  
}  
  
// a get method to get employee name  
public String getempNam ()  
{  
return empNam;  
}  
  
  
// a get method to figure out  the employee salary  
public double getempSal ()  
{  
return empSal;  
}  
  
// a get method to get the designation  
public String getempDes ()  
{  
return empDes;  
}  
  
@Override  
public String toString ()  
{  
String res = "employee Name: " + empNam + ", empDesignation : " + empDes + ", Employee Salary : " + empSal;  
  
return res;  
}  
}  
  
// main class  
public class LazyLoadExample  
{  


public static void main (String [] args)  
{  
// ContactListProxy class   
IcontctList contListObj = new ContactListProxy ();  
  
  
// instant of the compny class  
Company compObj = new Company ("JTP", "India", "+91-011-59502347", contListObj);  
  
System.out.println ("Compny Name: " + compObj.getCompanyName ());  
System.out.println ("Compny Address: " + compObj.getCompanyAddress ());  
System.out.println ("Compny Contact No.: " + compObj.getCompanyContactNo () + "\n");  
System.out.println ("Requesting for the contact list ...");  
  
contListObj = compObj.getcontList ();  
List<Employees> employeeList = contListObj.getEmploList ();  
  
 
for (Employees emp : employeeList)   
{  
System.out.println (emp);  
}  
}  
}  

Output:

Lazy loading in Java

We have created an instance of the ContactListProxy class in the code. The list of employees has not yet been made. This is because the list of employees is not currently necessary. When the list of workers is required, the function getEmployeeList () is called, and the list is generated at the same time, illustrating that the production of the list of employees is postponed until required.

Lazy initialization:

The Lazy Initialization technique shows how to check a class field's value when its use is necessary. If the value of the class field is null, the field is modified with the correct value before being returned. The same is demonstrated by the example below.

LazyLoadingExample.java

import java.util.Map;  
import java.util.HashMap;  
import java.util.Map.Entry;  
enum CarTypes   
{  
Hyundai ,  
suzuki,  
Ferrari  
}  
  
class CarModel   
{  
// a class field that keeps CarTypes as the key and its object as the value
private static Map<CarTypes, CarModel> typeMap = new HashMap<>();  
  
// private(access specifier) constructor of the class CarModel 
private CarModel (CarTypes type)   
{  
  
}  
  
public static CarModel getCarByTypeName (CarTypes type)  
{  
CarModel carObj;  
  
// load the type in the map typeMap  if type is not present 
if (!typeMap.containsKey(type))   
{  
  
carObj = new CarModel (type);  
typeMap.put (type, carObj);  
}   
else   
{  
// if present currently  
carObj = typeMap.get (type);  
}  
  
return carObj;  
}  
  
public static void displayAll ()  
{  
// calculation of the size of the map  
int size = typeMap.size ();  
  
// displaying when  map isn’t empty  
if (size > 0)   
{  
  
System.out.println (" instances created = " + size);  
  
// looping through each entry of the typeMap, displaying them  
for (Entry<CarTypes, CarModel> entry : typesMap.entrySet())   
{  
String car = entry.getKey().toString();  
car = Character.toUpperCase (car.charAt (0)) + car.substring (1);  
System.out.println (car);   
}  
  
System.out.println ();  
}  
}  
}  
public class LazyLoadExample  
{  
public static void main (String args [])  
{  
CarModel.getCarByTypeName (CarTypes.suzuki);  
CarModel.displayAll ();  
CarModel.getCarByTypeName (CarTypes.Ferrari);  
     CarModel.displayAll ();  
     CarModel.getCarByTypeName (CarTypes.Hyundai );  
      CarModel.displayAll ();  
      }  
}  

Output:

Lazy loading in Java

The lazy initialization of the map field is done in the code by the getCarByTypeName () method. It begins by determining whether the requested car type is present or not. If it isn't already there, the relevant car type is created and then loaded onto the map. Take note that the Cars class's function Object () {[native code]} has been purposefully made secret. The private function Object () {[native code]} makes sure that an object of the class Cars can never be created. A suitable instance of the class Cars is only produced or loaded when necessary because an instance of the class Cars is only created when the method getCarByTypeName () is used.


Related Topics

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.