SE450: Singleton: Cloning and serialization [22/32] Previous pageContentsNext page

Dissallow cloning in singleton classes.

final class SLinux implements S {
  // ...
  private Object readResolve() throws java.io.ObjectStreamException {
    return SObject.get();
  }
}
final class SOther implements S {
  // ...
  private Object readResolve() throws java.io.ObjectStreamException {
    return SObject.get();
  }
}

readResolve() is called after an object is deserialized.

Normally readResolve() cleans up the object a little and returns this, but here we want it to throw away the deserialized object.

Previous pageContentsNext page