Singletons auf die faule Art

Wir hatten heute eine kurze Diskussion über Singletons und die Art und Weise ihrer Erzeugung, speziell wenn man sie faul (lazy) erzeugen möchte. Die Wikipedia hat dazu diesen schönen Eintrag – On Demand Holder Idiom:

In software engineering, the Initialization on Demand Holder idiom (design pattern) is a lazy-loaded singleton. The idiom can be implemented in both single-threaded/serial and concurrent environments, but care must be taken to correctly implement the idiom under concurrent conditions.

Ganz besondern wichtig ist die Erklärung, warum Lazy in diesem Fall so und nicht anders funktioniert:

The implementation relies on the well-specified initialization phase of execution within the Java Virtual Machine (JVM); see section 12.4 of Java Language Specification (JLS) for details.

When the class Something is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition LazyHolder within it is not initialized until the JVM determines that LazyHolder must be executed. The static class LazyHolder is only executed when the static method getInstance is invoked on the class Something, and the first time this happens the JVM will load and initialize the LazyHolder class.