Friday, May 13, 2011

What is the best way to implement Singleton pattern

We use singleton pattern when we need only one instance to be created. Why do we need to create only one instance.
* Object creation and destruction might be a high expensive task.
* Object might share some information need to be accessed through out the system. If multiple instance are there. Different different classes will see different different values.

We can find many articles on how to implement Singleton pattern. The best solution I found so far is below.

public class Singleton {

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

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

}

We can guaraty that above is lazily loaded and thread safe. if you don't need it to be loaded lazily use below. that is the simplest.


public class Singleton {

private static Singleton instance = new Singleton();

public static Singleton getInstance() {
return instance;
}

}


As I remember in head first design pattern book, after saying so many stories they finally has given double locking solution like below. they talked much about volatile and double locking there.

class Singleton {

private static volatile Singleton instance;

public static Singleton getInstance(){
if(instance == null){
syncronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

}


OK Still I can't guarantee that only one instance is created for all scenarios. With java reflection we can call private constructor and create a new object as below.


Class cl = Class.forName("Singleton");
java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
c[0].setAccessible(true);
Singleton instance2 = (Singleton) c[0].newInstance();


There is a way to prevent that. We can implement Singleton by using enums. By default enums are singleton. As I found Enums can't be instantiate through reflection.


enum EnumSingleton {
SINGLETON;

public void test() {
System.out.println("This is also a singleton " + this);
}

private EnumSingleton(){
System.out.println("Constructing the singleton ...");
}

}

you can get the singleton object through EnumSingleton.SINGLETON and call test() method.

So what do you think what is the best last one or first one. I prefer the first one.

No comments:

Post a Comment