Monday, September 26, 2005

Seralizing a Singleton - More on readResolve method

This refers to my earlier post on Sep 21 regarding Serializing a Singleton. Here are a few more pointers for readResolve method:
  • Use a readResolve method to protect the 'instance-control invariants' of singletons and other instance-controlled classes. Consider the following Singelton class


public class Elvis {
private Elvis() {
...
}
... // Remainder omitted
}

  • This class would no longer be a singleton if the words “implements Serializable” were added to its declaration.
  • If the Elvis class is made to implement Serializable, the following readResolve method suffices to guarantee the singleton property:


private Object readResolve() throws ObjectStreamException {
// Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}

  • A readResolve method is necessary not only for singletons, but for all other instance controlled classes.
  • A second use for the readResolve method is as a conservative alternative to the defensive readObject method.
  • Following readResolve method can be used in lieu of the defensive readObject method:


// The defensive readResolve idiom
private Object readResolve() throws ObjectStreamException {
return new Period(start, end);
}

  • The accessibility of the readResolve method is significant.
    • A readResolve method on a final class, such as a singleton, it should be private.
    • For a readResolve method on a non final class, consider its accessibility. If it is private, it will not apply to any subclasses. If it is package-private, it will apply only to subclasses in the same package. If it is protected or public, it will apply to all subclasses that do not override it.

No comments:

Total Pageviews

Reading List - 05-Mar-23

Talking to #AI may be the most important job skill of this century ( JohnGoodPasture ) Role of account management over the years. It’s a ro...