Sobes.tech
Junior — Middle

How can deferred initialization of objects be applied in your code?

sobes.tech AI

Answer from AI

Lazy initialization in Java is used to create an object only at the moment of its first use, rather than at class loading or parent object creation. This helps save resources and speeds up program startup.

Example implementation using lazy initialization and the Singleton pattern:

public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {
        // private constructor
    }

    public static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

In Java 8+ you can also use the java.util.function.Supplier class or Optional for lazy initialization, or use Lazy<T> from third-party libraries.

In a multithreaded environment, it is advisable to use synchronization or declare the instance as volatile for correct lazy initialization.