Probably everyone has used Singleton pattern and following is a typical implementation:
I came across another implementation that to be frank I never thought was used to implement singletons.
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;
}
}
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.
public class Single {
private static Single sing;
static {
sing = new Single ();
}
private Single () {
}
public static Single getInstance () {
return sing;
}
}
1 comment:
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
Post a Comment