The Lurker
Stupid Java tricks: singleton without explicit synchronization
A long time ago, the synchronized
construct was relatively slow. More recently, a whole lot of people still thought it was pretty slow, even though it wasn't any more. Because of that early reality, and the lingering belief in it after performance was substantially improved, techniques such as "double-checked locking" (which was never correct) and clever application of volatile
(which were just as theoretically incorrect until Java 1.5 tightened up the definition of volatile
, albeit to a standard which real JVMs already upheld anyway) were developed. Bob Lee described one in his blog recently: using a static inner class containing a statically initialized field which holds the singleton.
It's a clever trick; the Java code need contain no explicit synchronization, because the JVM guarantees that the inner "holder" class (and therefore its static field) is initialized before the caller accesses the holder's static field; at the same time, because the class is only accessed when a caller wants to get the field, the singleton is instantiated lazily. But is it useful?
The advantage is that you don't need to use a synchronized
block in getInstance()
. There's basically no disadvantage at run time (ignoring that there will be one extra class loaded in your JVM, which is pretty trivial). There is a disadvantage in readability, because (since it depends on a property of class loading that people generally take for granted) why it works probably isn't obvious.
Can you think of a case where (a) getInstance()
performance is so critical that you can't afford the overhead of a synchronized
block, but (b) waiting for lazy initialization on the first call is OK? I can't.
On the other hand, it might make a good interview question for people who rate themselves "ten out of ten" as Java programmers.
All timestamps are Melbourne time.