Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot

Wiki Markup
The singleton design pattern's intent is succinctly described by the seminal work of \[[Gamma 95|AA. Java References#Gamma 95]\]:

Ensure a class only has one instance, and provide a global point of access to it.

"Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets." [When is a Singleton not a Singleton?]. Other applications of singletons involve maintaining performance statistics, system monitoring and logging, implementing printer spoolers or as simple as ensuring that only one audio file plays at a time.

A typical implementation of the Singleton pattern in Java is the creation of a single instance of the Singleton class that encloses a private static instance field.

The instance can be created using lazy initialization, which means that the instance is not created when the class loads but when it is first used.

Noncompliant Code Example

When the getter method is called by two (or more) threads or classes simultaneously, multiple instances of the Singleton class might result if one neglects to synchronize access.

Code Block
bgColor#FFcccc
class MySingleton {
  private static MySingleton _instance;

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

  // lazy initialization
  // error, no synchronization on method access

  public static MySingleton getInstance() {
    if (_instance == null) {
     _instance = new MySingleton();
    }
    return _instance;
  }

  // Remainder of class definition 
}

Noncompliant Code Example

Multiple instances can be created even if you add a synchronized(this) block to the constructor call.

Code Block
bgColor#FFcccc
// Also an error, synchronization does not prevent
// two calls of constructor.
public static MySingleton getInstance() {
 if (_instance == null) {
   synchronized (MySingleton.class) {
      _instance = new MySingleton();
   }
 }
 return _instance;
}

Compliant Solution

To avoid these issues, make getInstance() a synchronized method.

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;
   }
   // Remainder of class definition 
}

Applying a static modifier to the getInstance() method which returns the Singleton allows the method to be accessed subsequently (after the initial call) without creating a new object.

Noncompliant Code Example

Another solution for Singletons to be thread-safe is double-checked locking. Unfortunately, it is not guaranteed to work because compiler optimizations can force the assignment of the new Singleton object before all its fields are initialized.

Code Block
bgColor#FFcccc
// double-checked locking
public static MySingleton getInstance() {
 if (_instance == null) {
   synchronized (MySingleton.class) {
     if (_instance == null) {
        _instance = new MySingleton();
     }
   }
 }
}

Noncompliant Code Example

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

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 MSC37-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.

Compliant Solution

Wiki Markup
This compliant solution takes into account the garbage collection issue described above. A class is not garbage collected until the {{ClassLoader}} object used to load it itself becomes eligible for garbage collection. An easier scheme to prevent the garbage collection is to ensure that there is a direct or indirect reference to the singleton object to be preserved, from a live thread. This compliant solution demonstrates this method (adopted from \[[Patterns 02|AA. Java References#Patterns 02]\]). 

Code Block
bgColor#ccccff
public class ObjectPreserver implements Runnable {
  private static ObjectPreserver lifeLine = new ObjectPreserver();
  // Neither this class, nor HashSet will be garbage collected.
  // References from HashSet to other objects will also exhibit this property
  private static HashSet protectedSet = new HashSet();
  private ObjectPreserver() {
    new Thread(this).start();  // keeps the reference alive
  }
  public synchronized void run(){
  try {
    wait();
  }
  catch(InterruptedException e) { e.printStackTrace(); }
}

  // Objects passed to this method will be preserved until
  // the unpreserveObject method is called
  public static void preserveObject(Object o) {
    protectedSet.add(o);
  }

  // Unprotect the objects so that they can be garbage collected
  public static void unpreserveObject(Object o) {
     protectedSet.remove(o);
  }
}

Wiki Markup
To be fully compliant, it must be ensured that the class obeys the _Singleton_ pattern's design contract. It is unreasonable to use the class for anything else, for example, as a method to share global state. \[[Daconta 03|AA. Java References#Daconta 03]\]

Risk Assessment

Using lazy initialization in a Singleton without synchronizing the getInstance() method may lead to multiple instances and can as a result violate the expected contract.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON33- J

low

unlikely

medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

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"


CON32-J. Use notifyAll() instead of notify() to resume waiting threads      09. Concurrency (CON)      CON34-J. Avoid deadlock by requesting fine-grained locks in the proper order