public class Singleton {
    private static Singleton instance;
    //public static int i =1 ;
    private Singleton() {
    }
    public static Singleton getInstance() { // Using Double Checked Locking method
        if (instance == null) {
            synchronized (instance) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        //i++;
        return instance;
    }
    protected Object clone() throws CloneNotSupportedException
    {
        throw new CloneNotSupportedException();
    }
}
http://www.roseindia.net/javatutorials/J2EE_singleton_pattern.shtml
We need to override clone() method as well so no one should create a new Instance using clone.
After this even, one can create multiple instances of a Sing class in a Clustered Enviroonment coz in a clustered enviro, we have a heap for each node. So, even if we create an instance, a new instance can be created on other node.
How to avoid this :  we'll talk in next post :)
No comments:
Post a Comment