While searching on Stack Overflow for solutions to problems, I notice certain terms and phrases that are mentioned frequently. One of the most common I see is lazy initialization. Why would we want anything to be lazy? Lazy initialization in a nutshell is the idea of delaying initialization of an object until later when it is needed. When an application creates many objects, taxing operations performed by each object can add up. If you don’t need those operations right away then why would you perform them immediately and bog down the system?
public class LazyInit {
private static Resource resource;
public static Resource getResource() {
if (resource == null) {
resource = new Resource();
}
return resource;
}
}
Using a code snippet taken from an article published by Maciej Najbar, you can see an example for a single thread implementation. For those that have used the Singleton design pattern this may look familiar. The class creates a placeholder for the Resource object name resource. Using the getResource() method the object is checked to see if it has been initialized with a value or is null. If null, it is then assigned with a value which is returned otherwise it just returns the value already assigned. This allows the programmer to create conditions on when the initialization occurs with the getResource() method rather than in the constructor at object creation.
Examples on when it may pay to be lazy
- Loading images in a web application
- Java Spring Boot Beans
- Database connections
- Blog posts
As with everything there are some downsides to consider. Lazy loading is more taxing on the system than just initializing the object. This is why everything isn’t implemented that way. Some systems may need these objects to be created right away to be configured correctly. Also, it may be harder to debug since errors or exceptions won’t be thrown until initialization. As with anything in programming there are both pros and cons to consider before implementing. Make sure to weigh the costs on the system before adding a lazy loading to your application.
Resources:
Najbar, M. (2019, January 23). Lazy initialisation - what's a correct implementation? Medium. Retrieved September 19, 2021, from https://medium.com/android-news/lazy-initialisation-whats-a-correct-implementation-64c4638561e.
Maayan, G. D. (2020, December 25). Don't be LAZY: 3 problems with lazy loading and when to use eager loading. Hacker Noon. Retrieved September 19, 2021, from https://hackernoon.com/dont-be-lazy-3-problems-with-lazy-loading-and-when-to-use-eager-loading-qq1d34cl.