Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The singleton design pattern's intent is succinctly described by the seminal work of Gamma et al. and colleagues [Gamma 1995]:

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

Because there is only one Singleton 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" [Fox 2001]. Other applications of singletons involve maintaining performance statistics, system monitoring and logging system activity, implementing printer spoolers, or and even tasks such as ensuring that only one audio file plays at a time. Classes that contain only static methods are good candidates for the Singleton pattern.

...

A class that implements the singleton design pattern must prevent multiple instantiations. Relevant techniques include the following:

  • making Making its constructor private.
  • employing Employing lock mechanisms to prevent an initialization routine from running being run simultaneously by multiple threads.
  • ensuring Ensuring the class is not serializable.
  • ensuring Ensuring the class cannot be cloned.
  • preventing Preventing the class from being garbage-collected if it was loaded by a custom class loader.

Noncompliant Code Example (

...

Nonprivate Constructor)

This noncompliant code example uses a non-private nonprivate constructor for instantiating a singleton.:

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

  protected MySingleton() {    
    instance = new MySingleton();
  }

  public static synchronized MySingleton getInstance() {    
    return instance;
  }
}

A malicious subclass may extend the accessibility of the constructor from protected to public, allowing untrusted code to create multiple instances of the singleton. Also, the class field Instance has not been declared final.

...

Code Block
bgColor#ccccff
class MySingleton {
  private static final MySingleton instance = new MySingleton();

  private MySingleton() {    
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

  public static synchronized MySingleton getInstance() {    
    return instance;
  }
}

...

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

  private MySingleton() {    
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

  // Lazy initialization
  public static MySingleton getInstance() { // Not synchronized
    if (instance == null) {
      instance = new MySingleton();
    }
    return instance;
  }
}

...

Multiple instances can be created even when the singleton construction is encapsulated in a synchronized block., as in this noncompliant code example:

Code Block
bgColor#FFcccc
public static MySingleton getInstance() {
  if (instance == null) {
    synchronized (MySingleton.class) {
      instance = new MySingleton();
    }
  }
  return instance;
}

This is because The reason multiple instances can be created in this case is that two or more threads may simultaneously see the field instance as null in the if condition and enter the synchronized block one at a time.

...

To address the issue of multiple threads creating more than one instance of the singleton, make getInstance() a synchronized method.:

Code Block
bgColor#ccccff
class MySingleton {
  private static MySingleton instance;

  private MySingleton() {
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

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

...

Another compliant solution for implementing thread-safe singletons is the correct use of the double-checked locking idiom.:

Code Block
bgColor#ccccff
class MySingleton {
  private static volatile MySingleton instance;

  private MySingleton() {
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

  // Double-checked locking
  public static MySingleton getInstance() {
    if (instance == null) {
      synchronized (MySingleton.class) {
        if (instance == null) {
          instance = new MySingleton();
        }
      }
    }
    return instance;
  }
}

This design pattern is often implemented incorrectly . Refer to rule (see LCK10-J. Use a correct form of the double-checked locking idiom for more details on the correct use of the double-checked locking idiom).

Compliant Solution (Initialize-on-Demand Holder Class Idiom)

This compliant solution uses a static inner class to create the singleton instance.:

Code Block
bgColor#ccccff
class MySingleton {
  static class SingletonHolder {
    static MySingleton instance = new MySingleton();
  }

  public static MySingleton getInstance() {
    return SingletonHolder.instance;
  }
}

This approach is known as the initialize-on-demand holder class idiom. Refer to rule  (see LCK10-J. Use a correct form of the double-checked locking idiom for more information).

Noncompliant Code Example (Serializable)

...

Code Block
bgColor#FFcccc
class MySingleton implements Serializable {
  private static final long serialVersionUID = 6825273283542226860L;
  private static MySingleton instance;

  private MySingleton() {
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

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

A singleton's constructor cannot install checks to enforce the requirement that the class is instantiated only instantiated once because deserialization can bypass the object's constructor.

...

Adding a readResolve() method that returns the original instance is insufficient to enforce the singleton property. This technique is insecure even when all the fields are declared transient or static.

Code Block
bgColor#FFcccc
class MySingleton implements Serializable {
  private static final long serialVersionUID = 6825273283542226860L;
  private static MySingleton instance;

  private MySingleton() {
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

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

  private Object readResolve() {
    return instance; 
  }
}

...

Upon deserialization, the field MySingleton.untrusted is reconstructed before MySingleton.readResolve() is called. Consequently, Untrusted.captured is assigned the deserialized instance of the crafted stream instead of MySingleton.instance. This issue is pernicious when an attacker can add classes to exploit the singleton guarantee of an existing serializable class.

Noncompliant Code Example (

...

Nontransient Instance Fields)

This serializable noncompliant code example uses a non-transient nontransient instance field str.:

Code Block
bgColor#FFcccc
class MySingleton implements Serializable {
  private static final long serialVersionUID =
      2787342337386756967L;
  private static MySingleton instance;
  
  // non-transientNontransient instance field 
  private String[] str = {"one", "two", "three"}; 
                 
  private MySingleton() {
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

  public void displayStr() {
    System.out.println(Arrays.toString(str));
  }
 
  private Object readResolve() {
    return instance;
  }
}

"If a singleton contains a nontransient object reference field, the contents of this field will be deserialized before the singleton’s singleton'€™s readResolve method is run. This allows a carefully crafted stream to 'steal' a reference to the originally deserialized singleton at the time the contents of the object reference field are deserialized" [Bloch 2008].

...

Stateful singleton classes must be nonserializable. As a precautionary measure, classes that are serializable must not save a reference to a singleton object in their nontransient or nonstatic instance variables. This precaution prevents the singleton from being indirectly serialized.

...

Code Block
bgColor#ccccff
public enum MySingleton {
  ; // emptyEmpty list of enum values

  private static MySingleton instance;

  // non-transientNontransient field
  private String[] str = {"one", "two", "three"};

  public void displayStr() {
    System.out.println(Arrays.toString(str));
  }	 
}

...

Code Block
bgColor#FFcccc
class MySingleton implements Cloneable {
  private static MySingleton instance;

  private MySingleton() {
    // privatePrivate constructor prevents
    // instantiation by untrusted callers
  }

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

Compliant Solution (Override clone() Method)

Avoid To avoid making the singleton class cloneable by , do not implementing implement the Cloneable interface and do not deriving derive from a class that already implements it.

...

Code Block
bgColor#ccccff
class MySingleton implements Cloneable {
  private static MySingleton instance;

  private MySingleton() {
    // privatePrivate constructor prevents instantiation by untrusted callers
  }

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

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

See rule OBJ07-J. Sensitive classes must not let themselves be copied for more details about preventing misuse of the clone() method.

...

A static singleton becomes eligible for garbage collection when its class loader becomes eligible for garbage collection. This usually happens when a nonstandard (custom) class loader is used to load the singleton. This noncompliant code example prints different values of the hash code of the singleton object from different scopes.:

Code Block
bgColor#FFcccc
  {
  ClassLoader cl1 = new MyClassLoader();
  Class class1 = cl1.loadClass(MySingleton.class.getName());
  Method classMethod = 
      class1.getDeclaredMethod("getInstance", new Class[] { });
  Object singleton = classMethod.invoke(null, new Object[] { });
  System.out.println(singleton.hashCode());
}

ClassLoader cl1 = new MyClassLoader();
Class class1 = cl1.loadClass(MySingleton.class.getName());
Method classMethod = 
    class1.getDeclaredMethod("getInstance", new Class[] { });
Object singleton = classMethod.invoke(null, new Object[] { } );
System.out.println(singleton.hashCode());

Code that is outside the scope can create another instance of the singleton class even though the requirement was to use only the original instance.Because a singleton instance is associated with the class loader that is used to load it, it is possible to have multiple instances of the same class in the JVMJava Virtual Machine. This situation typically happens occurs in J2EE containers and applets. Technically, these instances are different classes that are independent of each other. Failure to protect against multiple instances of the singleton may or may not be insecure depending on the specific requirements of the program.

...

This compliant solution demonstrates this technique. It prints a consistent hash code across all scopes. It uses the ObjectPreserver class [Grand 2002] described in rule TSM02-J. Do not use background threads during class initialization.

...

Using improper forms of the singleton Singleton design pattern may lead to creation of multiple instances of the singleton and violate the expected contract of the class.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC07-J

lowLow

unlikelyUnlikely

mediumMedium

P2

L3

Automated Detection

Tool
Version
Checker
Description
Coverity7.5

SINGLETON_RACE
UNSAFE_LAZY_INIT
FB.LI_LAZY_INIT_UPDATE_STATIC
FB.LI_LAZY_INIT_STATIC

Implemented

Related Guidelines

MITRE CWE

CWE-543. , Use of Singleton pattern Pattern without synchronization Synchronization in a multithreaded contextMultithreaded Context

Bibliography

[Bloch 2008]

Item 3. , "Enforce the singleton property Singleton Property with a private constructor Private Constructor or an enum type; and Type"
Item 77. For instance control, prefer enum types to readResolve, "For Instance Control, Prefer enum Types to readResolve"

[Daconta 2003]

Item 15. Avoiding singleton pitfalls, "Avoiding Singleton Pitfalls"

[Darwin 2004]

Section 9.10, "Enforcing the Singleton Pattern"

[Fox 2001]

When Is a Singleton Not a Singleton? 

[Gamma 1995]

Singleton

[Grand 2002]

Chapter 5, "Creational Patterns," section "Singleton"

[JLS 20052015]

Chapter 17, "Threads and Locks"

 

...