[Ilja]: In fact, it seems that this solution might in fact not work as expected. Indeed, it doesn't work reliably on JDK's prior to JDK 5; this is acknowledged in a "Watch It!" blurb at the bottom of the page in HFDP (p. 182). Note that the Developerworks article linked above is from 2002. The revised
Java memory model that came out with JDK 5 did strengthen the semantics of volatile, such that the double-checked locking code above should work for JDK 5 and later. See the
JSR-133 FAQ for more info.
I'm perplexed as to why HFDP omitted the Initialization On Demand Holder idiom, as it's easier to understand and code, and works for earlier JDK's as well.
I'm also a bit irritated that p. 180 has them repeating the "I heard synchronization is expensive" myth without pointing out that it's much faster now than it was in the earliest days of Java, and it's really pretty rare that synchronization would cause a perceptible performance problem in a short method like getInstance(). Too much bad, convoluted code has been written by people bending over backwards to avoid synchronization. (Especially prior to JDK 5 and the java.util.concurrent packages.) Grumble, grumble.