Search code examples
javaobjectserializationsingletoneffective-java

Singleton classes serializable


Can anyone explain this paragraph: [copied from Effective Java Joshua Bloch 3rd edition Chapter 2 Item 3 ]

To make a singleton class that uses either of these approaches (i.e. keeping the constructor private and exporting a public static member to provide access to the sole instance) serializable , it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, declare all instance fields transient and provide a readResolve method. Otherwise, each time a serialized instance is deserialized, a new instance will be created, leading, in the case of our example, to spurious Elvis sightings. To prevent this from happening, add this readResolve method to the Elvis class:

//  readResolve method  to  preserve    singleton   property 
private Object  readResolve()   
{ 
//  Return  the one true    Elvis   and let the garbage collector //    take    care    of  the Elvis   impersonator. 
return  INSTANCE; 
}

Solution

  • Using serialization/deserializaiton we can create many objects which leads to singleton failure. So to avoid this we have to implement the readResolve() method. During deserializaiton, Before giving the deserialized object it will check the readResolve() method. If you override and give your singleton instance then no new object will be created.