Search code examples
javasingletonclassloader

Why in Eager initialization, the instance of the singleton class which created at the time of class loading could consider a drawback?


I know that static variables are loaded at runtime, and although I thought I understand the issue, I had troubles with the next Eager Initialization Singelton implementation:

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.

public class EagerInitializedSingleton {

private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}

public static EagerInitializedSingleton getInstance(){
    return instance;
}

}

If the class's constructor is private, how the class instance can be created at the time of class loading? It has only one public entry point, which the client has to call explicitly, right?


Solution

  • Why in Eager initialization, the instance of the singleton class which created at the time of class loading could consider a drawback?

    As the text you quoted says:

    "... it has a drawback that [the] instance is created even though client application might not be using it."

    Why is that a drawback?

    Because:

    • it might be computationally expensive (and increase startup time) to create the instance
    • the instance might take up a lot of memory.

    If the class's constructor is private, how the class instance can be created at the time of class loading?

    It is created when the initializing expression for instance is evaluated. That happens when the EagerInializedSingleton class is initialized ... which typically happens when the class is loaded.

    The expression calls the private constructor. But that is OK because a code in a class can see its own private fields / methods and constructors.

    Does it mean the class is getting loaded when the we call the getInstance method?

    Not necessarily. It could happen before then. But it won't happen after then1.

    1 - ... unless you have created an initialization dependency cycle.