Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: testing

...

The other range of Singleton related subtleties involve object serialization and cloning. Serialization allows objects to be constructed without invoking the constructor and in turn allows object replication. It is also possible to create a copy of the Singleton object by cloning it using the object's clone method whenever the Singleton class implements Cloneable directly or through inheritance. Both these conditions violate the Singleton Design Pattern's guarantees.

Compliant Solution

It is recommended that Singleton classes be made non-serializable. As a precautionary measure, (serializable) classes must never save a reference to a singleton object in its instance variables. The getInstance method should be used instead, whenever access to the object is required.

Wiki Markup
To address the cloning issue, do not make the _Singleton_ class cloneable. If it indirectly implements the {{Cloneable}} interface through inheritance, override the object's {{clone}} method and throw a {{CloneNotSupportedException}} exception from within it. \[[Daconta 03|AA. Java References#Daconta 03]\]

Code Block
bgColor#ccccff

class MySingleton {
  private static MySingleton _instance;

  private MySingleton() {
    // construct object . .
    //  private constructor prevents instantiation by outside callers
  }

  // lazy initialization
  public static synchronized MySingleton getInstance() {
    if (_instance == null) {
      _instance = new MySingleton();
    }
    return _instance;
  }

  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }

  // Remainder of class definition . . .
}

See MSC05-J. Make sensitive classes noncloneable for more details about restricting the clone() method.

Noncompliant Code Example

When the utility of a class is over, it is free to be garbage collected. A dynamic reference can however, cause another instance of the Singleton class to be returned. This behavior can be troublesome when the program needs to maintain only one instance throughout its lifetime.