Why private static field = new Singleton is not lazy in Java?

后端 未结 3 969
一个人的身影
一个人的身影 2021-01-18 12:45

I read a lot of articles about Singleton, in most of which authors said that this variation of Singleton in Java:

public class Singleton {
    private static         


        
3条回答
  •  长情又很酷
    2021-01-18 13:01

    Basically it's a matter of degrees of laziness. It's lazy in that it won't construct the singleton until the class is initialized, but it's eager in that there could be situations where you want to use the class without initializing the singleton itself.

    For example:

    public final class Singleton {
        private static final Singleton instance = new Singleton();
    
        private Singleton() {}
    
        public static Singleton getInstance() {
            return instance;
        }
    
        public static void sayHello() {
            System.out.println("Hello!");
        }
    }
    

    Calling Singleton.sayHello() will instantiate the singleton even if we don't want it to... so it's not as lazy as it could be.

    You can get round this using a nested type:

    public final class Singleton {
        private Singleton() {}
    
        public static Singleton getInstance() {
            return Holder.instance;
        }
    
        public static void sayHello() {
            System.out.println("Hello!");
        }
    
        private static class Holder {
            private static final Singleton instance = new Singleton();
        }
    }
    

    Now Singleton.Holder will only be initialized by using the getInstance method. It's lazy and thread-safe with no locking.

    In my experience, usually a singleton class's only static method is the getInstance method, in which case they're equivalent (assuming you don't use reflection to initialize the type somehow, for example).

提交回复
热议问题