Lazy Loading in Java
The concept of delaying the loading of an object until one needs it is known as lazy loading. In other words, it is the process of delaying the process of instantiating the class until required. Lazy loading is important in a scenario where the cost of creating objects is high, or usage of the object is rare in the program. Lazy loading is a technique that enhances the efficiency of the program. In this section, we will discuss lazy loading in detail.
Implementations of Lazy Loading
Virtual proxy is the memory saving process that promotes the postponement of object creation. Observe the following program.
Company Name: ABC Company Address: India Company Contact No.: +91-011-55512347 Requesting for the contact list ... Fetching the list of employees ... Employee Name: Mukesh, EmpDesignation : JSE, Employee Salary : 3452.67 Employee Name: Amit, EmpDesignation : ASE, Employee Salary : 22345.0 Employee Name: Naman, EmpDesignation : G4, Employee Salary : 3256.17 Employee Name: Vipul, EmpDesignation : SDE1, Employee Salary : 4895.34 Employee Name: Akhil, EmpDesignation : SDE2, Employee Salary : 2857.91
Explanation: In the code, we have instantiated the ContactListProxy class. At this point, the list of employees is not created. It is because the list of employees is not required at this point of time. When the list of employees is required, the method getEmployeeList() is invoked, and at the same time, the list of employees is created, which shows the creation of the list of employees is delayed until required.
The Lazy Initialization technique demonstrates the value check of a class field when its usage is required used. If that class field value is null, then the field gets updated with the proper value before it is returned. The following example illustrates the same.
File Name: LazyLoadingExample1.java
The number of instances created = 1 Mercedes The number of instances created = 2 Audi Mercedes The number of instances created = 3 Audi BMW Mercedes
Explanation: In the code, the getCarByTypeName() method does the lazy initialization of the map field. It first checks whether the asked car type is present or not. If not present, the concerned car type is instantiated and then loaded on the map. Note that the constructor of the class Cars is made private intentionally. The private constructor ensures that one cannot create an object of the class Cars at any time. An instance of the class Cars is only created when we invoke the method getCarByTypeName(), which shows that an appropriate instance of the class Cars is only created or loaded when required.
Next TopicRectangular Number in Java