×

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

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.