Skip to main content

Posts

Showing posts from December, 2009

Singleton pattern revisited in Java

Lets look at one the simple implementation of Singleton pattern in Java public class A { public static A a; private A () {} public static A getInstance() { if ( a == null ) { a = new A(); } return a; } } I'm arguing there is a major flaw in the implementation of getInstance() method, most of the old authors have simply translated all pattern implementation into Java from C++, remember Java Class-loaders work differently from C++. The above class is never loaded until we call A.getInstance() once, so what is the point of writing that thread safe, or validation code its all waste and we are simply introducing rubbish, simple implement Singleton pattern this way public class A { public static A a = new A(); private A () {} public static A getInstance() { return a; } }