adithya narayan wrote:Well, why would one require
thread-safe lazy initialization idiom
?
I was just going through the following link :
http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2
Form what little i understood, the JVM is intelligent enough to avoid dead-locks when
multiple threads simultaneously try instantiating objecs of a class. Correct me if i am wrong !
It's usually applied as an alternative to double-checked locking when eager initialization is deemed inappropriate.
This approach works, because the SingletonHolder class is loaded and initialized "just in time" when the Singleton's getInstance() method is first called, and the static Singleton instance of SingletonHolder gets initialized as part of this process. Indeed, according to the JLS, a JVM must ensure that initialization of a class is properly synchronized. This implies that, however many threads invoke Singleton's getInstance() method however many times, the static Singleton instance of the SingletonHolder class is initialized exactly once.
And just to be clear, eventhough in my opinion this particular lazy initialization idom is
far clearer, easier to understand and less prone to error than the double-checked locking approach, I'd seriously consider just using eager initialization.
Also, I tend to avoid the Singleton pattern altogether, so I'm definitely with Stephen and Winston on this.