Friday, July 13, 2007

Initialization on Demand Holder (IODH) Idiom Singleton

I read this short article about the controversial Singleton Pattern that explains the popular form of the pattern which is seen in so many Java applicaitons is basically flawed.

The conclusion of the article illustrates another approach using an inner class which is guaranteed to execute only once ensuring there is only one instance created (and is thread-safe).

The Java Language Specification (JLS) guarantees the object "instance" would not be initialised until someone calls getInstance() method.


public class Singleton {
static class SingletonHolder {
static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.instance;
}
}


Click to read article
Wiki on Initialization on Demand Holder pattern