Sobes.tech
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:

  1. 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;
    }
}
  1. Using Supplier or Optional with deferred initialization.

  2. In Java 8+, you can use java.util.concurrent.atomic.AtomicReference with 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.