Saturday, December 06, 2008

Why using static block for Singleton will not work in all cases

Probably everyone has used Singleton pattern and following is a typical implementation:


public class Single {
private static Single single;

// -- Rule#1: Make sure no one outside the class could call new
private Single () {
}

// -- Rule#2: Provide another channel to get an instance
public static Single getInstance () {
if (single == null) {
synchronized (Single.class) {
if (single == null) {
single = new Single ();
}
}
}
return single;
}
}
I came across another implementation that to be frank I never thought was used to implement singletons.

public class Single {
private static Single sing;

static {
sing = new Single ();
}

private Single () {
}

public static Single getInstance () {
return sing;
}
}
Even though its a tricky way but bluntly this is a wrong implementation for one simple reason: It does not work if the class is lazily loaded (Class.forName ("Single");) and constructor takes a parameter. So I would rather continue to stay with a good old implementation.

1 comment:

Unknown said...

Hi Ashish,

Although this isn't at first obvious, the first implementation is not thread safe. This is discussed in detail here:

http://www.ibm.com/developerworks/java/library/j-dcl.html

-Patrick