frictionlesspulley frictionlesspulley - 1 month ago 7
Java Question

How to deal with Singleton along with Serialization

Consider I have a Singleton class defined as follows.

public class MySingleton implements Serializable{
private static MySingleton myInstance;

private MySingleton(){

}
static{
myInstance =new MySingleton();
}
public static MySingleton getInstance(){
return MySingleton.myInstance;
}
}


The above definition according to me satisfies the requirements of a Singleton.The only additional behaviour added is that the class implements serializable interface.

If another class X get the instance of the single and writes it to a file and at a later point deserializes it to obtain another instance we would have two instances which is against the Singleton principle.

How can I avoid this or am I wrong in above definition itself.

Answer

The best way to do this is to use the enum singleton pattern:

public enum MySingleton {
  INSTANCE;
}

This guarantees the singleton-ness of the object and provides serializability for you in such a way that you always get the same instance.

More generally, you can provide a readResolve() method like so:

protected Object readResolve() {
  return myInstance;
}