Singleton via enum way is lazy initialized?

后端 未结 2 588
小鲜肉
小鲜肉 2020-12-04 13:53

This is a very wide-spread enum singleton code:

public enum enumClazz{
   INSTANCE
   enumClazz(){
     //do something
   }
}

and a bunch o

相关标签:
2条回答
  • 2020-12-04 14:01

    enum instance fields are not "initialized by a compile-time constant expression". They can't be, because only String and primitive types are possible types for a compile-time constant expression.

    That means that the class will be initialized when INSTANCE is first accessed (which is exactly the desired effect).

    The exception in the bold text above exists, because those constants (static final fields initialized with a compile-time constant expression) will effectively be inlined during compilation:

    class A {
      public static final String FOO = "foo";
    
      static {
        System.out.println("initializing A");
      }
    }
    
    class B {
      public static void main(String[] args) {
        System.out.println(A.FOO);
      }
    }
    

    Executing class B in this example will not initialize A (and will not print "initializing A"). And if you look into the bytecode generated for B you'll see a string literal with the value "foo" and no reference to the class A.

    0 讨论(0)
  • 2020-12-04 14:14

    The third point with bold style clarify that if the field is 'static final', the initialzation of the field is happened at complie-time

    Not exactly - it only applies to "static fields that are final and initialized by a compile-time constant expression":

    static final String = "abc"; //compile time constant
    static final Object = new Object(); //initialised at runtime
    

    In your case, the singleton will be initialised when the enum class is loaded, i.e. the first time enumClazz is referenced in your code.

    So it is effectively lazy, unless of course you have a statement somewhere else in your code that uses the enum.

    0 讨论(0)
提交回复
热议问题