Friday, April 22, 2011

My notes for an interview which I gues will help
Fact about SingleTon

1) if your singleTOn class implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.

2)SingleTon Class is not thread safe

if(instance == null) {
instance = new Singleton();
}

3) if you clone singleTon class, it will create a clone and there will be two different object will be created. You can print hashCode of each instance, it will be different

4) if you create synchronized method, it will always hit the performance whenever you
you create object.

public synchronized static Singleton getInstance() {
if(singleton == null) {
synchronized(Singleton.class) {
singleton = new Singleton();
}
System.out.println("Object created");
}
return singleton;
}

5) if you creat synchronized block, its not thread safe. Suppose control comes to
System.out.println("Object created"); statement and before returning 2nd thread come
here thread1 is out of synchornized block and again thread2 can enter block

public static Singleton getInstance() {
if(singleton == null) {
synchronized(Singleton.class) {
singleton = new Singleton();
}
System.out.println("Object created");
}
return singleton;
}

1 comment: