Reputation: 942
If I defined Class 'A' as a Singleton mean I am able to create only one object of the class 'A'. If I made it as Serializable and serialized it then How can i achieve the Singleton state of same object?
Upvotes: 1
Views: 1231
Reputation: 942
Before deserialization of any object one method gets called is the readResolve() so we can simply return the same state object from this method without actually deserializing it.
Please see below,
public final class MySingleton {
private MySingleton() { }
private static final MySingleton INSTANCE = new MySingleton();
public static MySingleton getInstance() { return INSTANCE; }
private Object readResolve() throws ObjectStreamException {
// instead of the object we're on,
// return the class variable INSTANCE
return INSTANCE;
}
}
Upvotes: 1
Reputation: 10224
To guarantee the uniqueness of a Serializable
singleton, you may need customize readResolve
method to return the singleton object instead of newly deserialized one. On the other hand, book "Effective Java" Item77 suggests that:
For instance control, prefer enum types to readResolve
Upvotes: 1
Reputation: 3025
Quoting Effective Java #77
, you should look at implementing readResolve
method.
The readResolve feature allows you to substitute another instance for the one created by readObject [Serialization, 3.7]. If the class of an object being deserial- ized defines a readResolve method with the proper declaration, this method is invoked on the newly created object after it is deserialized. The object reference returned by this method is then returned in place of the newly created object. In most uses of this feature, no reference to the newly created object is retained, so it immediately becomes eligible for garbage collection.
public class Elvis implements Serializable {
public static final Elvis INSTANCE = new Elvis();
// readResolve for instance control - you can do better!
private Object readResolve() {
//Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}
}
Upvotes: 3