Can anyone explain to me what is this means? especially the bold lines.
To make a singleton class serializable, it is not sufficient merely to add
implements Serializable
to its declaration. To maintain the singleton guarantee, you have to declare all instance fieldstransient
and provide areadResolve()
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, add thisreadResolve()
method to theElvis
class:// Singleton with static factory public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public static Elvis getInstance() { return INSTANCE; } public void leaveTheBuilding() { ... } } // 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; }
FYI: these lines are from Effective Java Book, Item 3