Initialization-on-demand holder idiom - When are classes loaded?

旧时模样 提交于 2020-02-22 14:45:37

问题


I have been looking at: https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom to understand a little bit more about Singletons.

My question is when exactly does the static inner class get Loaded and when does it get Initialised? My understanding is that classes can be loaded but remain uninitialised until initialisation is absolutely necessary.

If the class is not loaded, how is the private static inner class specified within the JVM?


回答1:


The exact time when a class is initialized, is specified in the Java® Language Specification, §12.4.1

§12.4.1. When Initialization Occurs

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • A static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

When a class is initialized, its superclasses are initialized (if they have not been previously initialized), as well as any superinterfaces (§8.1.5) that declare any default methods (§9.4.3) (if they have not been previously initialized). Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces.

The last bullet has been removed in Java 9

The time of class loading is not that fixed and may depend on implementation details, e.g. how the verifier has been implemented. But obviously, it has to happen before the initialization.

From the JVM’s point of view, the fact that this is a nested class has no special relevance. There is a symbolic reference to the inner class in the outer class’ constant pool, like there is for any other referenced class. It will be resolved when needed.



来源:https://stackoverflow.com/questions/50339119/initialization-on-demand-holder-idiom-when-are-classes-loaded

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!