1

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; 
}

2 Answers2

1

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.

Aslam a
  • 750
  • 10
  • 19
0

Imagine this scenario, your application runs and serializes the Singleton (refer as s1 from now on). Over the weekend the application is torn down and restarted. A new singleton is created when the process comes up (now is s2). While the application is running using s2 another object deserializes s1. You now have two singletons which are different objects living in the same application.

Hope this helps.

billy.mccarthy
  • 122
  • 1
  • 11