Different ways to write singleton in Java - Stack Overflow
Initialization on Demand Holder (IODH) idiom which requires very little code and has zero synchronization overhead. Zero, as in even faster than volatile
. IODH requires the same number of lines of code as plain old synchronization, and it's faster than DCL!
IODH utilizes lazy class initialization. The JVM won't execute a class's static initializer until you actually touch something in the class. This applies to static nested classes, too. In the following example, the JLS guarantees the JVM will not initialize instance
until someone calls getInstance()
:
static class SingletonHolder { static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; }
Read full article from Different ways to write singleton in Java - Stack Overflow
No comments:
Post a Comment