Search code examples
javasingletonlifecycle

What is meant by early initialization of a Singleton class in Java


I am not quite clear on what is meant by the term Early initialization of a Singleton class. Also it would be helpful to understand the life cycle of a Singleton class.


Solution

  • Well Lazy initialization means that you do not initialize objects until the first time they are used.

    Early initialization is just reverse, you initialize a singleton upfront at the time of class loading.

    There are ways to do early initialization, one is by declaring your singleton as static.

    Following as an example:

    public class SingletonClassEarly {
        private static SingletonClassEarly sce = new SingletonClassEarly();
        private SingletonClassEarly() {} // make it private
    
        public static SingletonClassEarly getInstance() {
            return sce;
        }
    }
    

    As per the lifecycle this singleton is loaded after JVM starts up and when class is initialized. It gets unloaded by JVM when shutting down/exiting.