问题
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 ofT
is created.- A
static
method declared byT
is invoked.- A
static
field declared byT
is assigned.- A
static
field declared byT
is used and the field is not a constant variable (§4.12.4).T
is a top level class (§7.6) and anassert
statement (§14.10) lexically nested withinT
(§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