Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

April 29, 2010

Singleton Class (very Good one)

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: