Tuesday, July 05, 2005

The Singleton and Double Checked Locking

The "Double-Checked Locking is Broken" Declaration "If the singleton you are creating is static (i.e., there will only be one Helper created), as opposed to a property of another object (e.g., there will be one Helper for each Foo object, there is a simple and elegant solution.

Just define the singleton as a static field in a separate class. The semantics of Java guarantee that the field will not be initialized until the field is referenced, and that any thread which accesses the field will see all of the writes resulting from initializing that field.

class HelperSingleton {
static Helper singleton = new Helper();
}"

I've had this happen in real life many times, where people expect DCL to work. It doesn't no matter how hard you try (and I've had seen some really smart people try).

There is no way around it except for Java 1.5.

With something like Spring and PicoContainer, though, the Singleton pattern is fairly inherent - a configuration option for an object rather than something you specify in code.

No comments: