1

I'm wondering why the 2nd variant is considered more lazy, that he first.

1.

public class Singleton {
        private static Singleton singleton=new Singleton();
    
        private Singleton(){}
    
        static public Singleton getInstance(){
            return singleton;
        }
    }

The singleton above is initialized when the class is loaded, that is when getInstance() is called. Because classes are loaded when they are required. It's not loaded before getInstance() call. Is that correct?

But the sinleton below is also initialized when getInstance() is called. So can't understand the benefits of the 2nd variant:

2.

public class SingletonWithHolder {

    private SingletonWithHolder() {
    }

    public static SingletonWithHolder getInstance() {
        return Holder.instance;
    }

    private static class Holder {
        private final static SingletonWithHolder instance = new SingletonWithHolder();
    }

   
}
Ekaterina
  • 1,642
  • 3
  • 19
  • 36

0 Answers0