Singleton via enum way is lazy initialized?

后端 未结 2 601
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题