Junior — Middle
How is deferred initialization of objects implemented in software systems?
sobes.tech AI
Answer from AI
Lazy initialization is a technique where an object is created only at the moment of its first use, rather than at program load or start. This helps save resources and speeds up application startup.
In Java, lazy initialization is often implemented using:
- Lazy loading with a null check before object creation.
- Singleton pattern with lazy initialization.
- java.util.concurrent.atomic.AtomicReference class or synchronized blocks for thread safety.
Example of lazy initialization:
public class LazyExample {
private ExpensiveObject obj;
public ExpensiveObject getObj() {
if (obj == null) {
obj = new ExpensiveObject();
}
return obj;
}
}
In Java 8+, you can use Supplier or Optional for a more elegant implementation.