Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added advice from Bloch 08 to a CS

...

Compliant Solution

It is recommended that stateful 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
If making a singleton class serializable is indispensable, ensure that only one instance of the class exists by adding a {{readResolve()}} method which can be made to return the original instance. The phantom instance obtained after deserialization is left to the judgment of the garbage collector. \[[Bloch 08|AA. Java References#Bloch 08]\]

Code Block
bgColor#ccccff

private Object readResolve() {
  return _instance;
}

Wiki Markup
\[[Bloch 08|AA. Java References#Bloch 08]\] suggests the use of an {{enum}} type as a replacement for traditional implementations (shown below). Functionally, this approach is equivalent to commonplace implementations. It ensures that only one instance of the object exists at any instant and also provides the serialization property since {{java.lang.Enum<E>}} extends {{Serializable}}.

Code Block
bgColor#ccccff

public enum MySingleton {
  _INSTANCE;
// other methods
}

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]\]

...

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Chapter 17, Threads and Locks|http://java.sun.com/docs/books/jls/third_edition/html/memory.html]
\[[Fox 01|AA. Java References#Fox 01]\] [When is a Singleton not a Singleton?|http://java.sun.com/developer/technicalArticles/Programming/singletons/]&nbsp;
\[[Daconta 03|AA. Java References#Daconta 03]\] Item 15: Avoiding Singleton Pitfalls;
\[[Darwin 04|AA. Java References#Darwin 04]\] 9.10 Enforcing the Singleton Pattern
\[[Gamma 95|AA. Java References#Gamma 95]\] Singleton
\[[Patterns 02|AA. Java References#Patterns 02]\] Chapter 5, Creational Patterns, Singleton
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 3: "Enforce the singleton property with a private constructor or an enum type"
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 543|http://cwe.mitre.org/data/definitions/543.html] "Use of Singleton Pattern in a Non-thread-safe Manner"

...