Junior — Middle
How can you initiate work with a lazy instance of an object?
sobes.tech AI
Answer from AI
Lazy initialization means creating an object only at the moment of the first access to it. In Java, this can be done in several ways:
- Using the Lazy Holder pattern:
public class MyClass {
private static class LazyHolder {
static final ExpensiveObject INSTANCE = new ExpensiveObject();
}
public static ExpensiveObject getInstance() {
return LazyHolder.INSTANCE;
}
}
-
Using
SupplierorOptionalwith deferred initialization. -
In Java 8+, you can use
java.util.concurrent.atomic.AtomicReferencewith a check and creation of the object on the first call.
Example with Supplier:
Supplier<ExpensiveObject> lazy = () -> new ExpensiveObject();
ExpensiveObject obj = lazy.get(); // object is created here
Thus, working with a lazy instance begins with calling a method or function that creates the object upon the first access.