[Translated from Wikipedia: http://en.wikipedia.org/wiki/initialization_on_deman_holder_idiom]
You may have heard that Singleton has thread security issues. Of course, you can solve this problem through synchronous locking. For more information, see this document.
In software engineering, initialization-on-demand holder refers to the singleton mode of delayed loading. In all Java versions, this method can achieve secure and efficient implementation of high-concurrency delayed initialization.
The code structure is as follows:
Public class something {private something () {} Private Static class lazyholder {Private Static final something instance = new something ();} public static something getinstance () {return lazyholder. instance ;}}
This implementation depends on the features in the JVM initialization phase, which are described in the Java language description. When a class is loaded by JVM, the class will go through the initialization process. Since this class does not have other static variables to be initialized, the initialization process will be completed smoothly. The static class lazyholder defined in the class will not be initialized until the JVM determines that lazyholder will be executed. When the static method getinstance is called, the static class lazyholder will be executed. When this happens for the first time, the JVM will load and initialize lazyholder.
Lazyholder initialization causes the static variable instance to be initialized because the external class (that is, lazyholder) executes the private constructor. Because the class initialization process is serialized (guaranteed by the Java language), no parallel synchronization operation is required.
In addition, because the static variable instance is written in the serial operation in the initialization phase, all subsequent concurrent calls to the getinstance method will return the same instance correctly without additional synchronization overhead.
Initialization-on-demand holder Idiom