The singleton design pattern's intent is succinctly described by the seminal work of Gamma et al. \[[Gamma 95|AA. Java References#Gamma 95]\Gamma and colleagues [Gamma 1995]: Wiki Markup
Ensure a class only has one instance, and provide a global point of access to it.
Wiki Markup |
---|
"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." \[[Fox 01|AA. Java References#Fox 01]\]. 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. |
Because 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" [Fox 2001]. Other applications of singletons involve maintaining performance statistics, monitoring and logging system activity, implementing printer spoolers, 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.
The Singleton pattern typically Typically, the Singleton pattern uses a single instance of a class that encloses a private static instance class 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 (nonprivate constructor)
A class that implements the singleton design pattern must prevent multiple instantiations. Relevant techniques include the following:
- Making its constructor private
- Employing lock mechanisms to prevent an initialization routine from being run simultaneously by multiple threads
- Ensuring the class is not serializable
- Ensuring the class cannot be cloned
- Preventing the class from being garbage-collected if it was loaded by a custom class loader
Noncompliant Code Example (Nonprivate Constructor)
This noncompliant This noncompliant code example uses a nonprivate constructor for instantiating a singleton.:
Code Block | ||
---|---|---|
| ||
class MySingleton { private static MySingleton INSTANCEinstance; protected MySingleton() { // private constructor prevents instantiation by untrusted callers INSTANCE instance = new MySingleton(); } public static synchronized MySingleton getInstance() { return INSTANCEinstance; } } |
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
Instance
has not been declared as final.
Compliant Solution (
...
Private Constructor)
This compliant solution reduces the accessibility of the constructor to private and immediately initializes the field INSTANCE
immediately Instance
, allowing it to be declared final. Singleton constructors must be private.
Code Block | ||
---|---|---|
| ||
class MySingleton { private static final MySingleton INSTANCEinstance = new MySingleton(); private MySingleton() { // privatePrivate constructor prevents instantiation by untrusted callers } public static synchronized MySingleton getInstance() { return INSTANCEinstance; } } |
Noncompliant Code Example (visibility across threads)
When the getter method is called by two (or more) threads simultaneously, multiple instances of the Singleton
class might result if access is not synchronized.
The MySingleton
class need not be declared final because it has a private constructor.
(Note that the initialization of instance
is done when MySingleton
is loaded, consequently it is protected by the class's initialization lock. See the JLS s12.4.2 for more information.)
Noncompliant Code Example (Visibility across Threads)
Multiple instances of the Singleton
class can be created when the getter method is tasked with initializing the singleton when necessary, and the getter method is invoked by two or more threads simultaneously.
Code Block | ||
---|---|---|
| ||
Code Block | ||
| ||
class MySingleton { private static MySingleton INSTANCEinstance; private MySingleton() { // privatePrivate constructor prevents instantiation by untrusted callers } // Lazy initialization public static MySingleton getInstance() { // Not synchronized if (INSTANCEinstance == null) { INSTANCEinstance = new MySingleton(); } return INSTANCEinstance; } } |
A singleton initializer method in a multithreaded program must employ some form of locking to prevent construction of multiple singleton objects.
Noncompliant Code Example (
...
Inappropriate Synchronization)
Multiple instances can be created even if when the singleton construction is encapsulated in a synchronized block., as in this noncompliant code example:
Code Block | ||
---|---|---|
| ||
public static MySingleton getInstance() { if (INSTANCEinstance == null) { synchronized (MySingleton.class) { INSTANCEinstance = new MySingleton(); } } return INSTANCEinstance; } |
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
instance
as null
in the if
condition and enter the synchronized block one at a time.
Compliant Solution (
...
Synchronized Method)
To address To avoid the issue of multiple threads creating more than one instance of the singleton, make getInstance()
a synchronized method.:
Code Block | ||
---|---|---|
| ||
class MySingleton { private static MySingleton INSTANCEinstance; private MySingleton() { // privatePrivate constructor prevents instantiation by untrusted callers } // Lazy initialization public static synchronized MySingleton getInstance() { if (INSTANCEinstance == null) { INSTANCEinstance = new MySingleton(); } return INSTANCEinstance; } } |
Compliant Solution (
...
Double-Checked Locking)
Another compliant solution for implementing thread-safe singletons is the correct use of the double-checked locking idiom. :
Code Block | ||
---|---|---|
| ||
class MySingleton { private static volatile MySingleton INSTANCEinstance; private MySingleton() { // privatePrivate constructor prevents instantiation by untrusted callers } // Double-checked locking public static MySingleton getInstance() { if (INSTANCEinstance == null) { synchronized (MySingleton.class) { if (INSTANCEinstance == null) { INSTANCEinstance = new MySingleton(); } } } return INSTANCEinstance; } } |
This design pattern is often implemented incorrectly . Refer to CON22(see LCK10-J. Do not use incorrect forms Use a correct form of the double-checked locking idiom for more details on the doublecorrect use of the double-checked locking idiom).
Noncompliant Code Example (Serializable singleton)
Compliant Solution (Initialize-on-Demand Holder Class Idiom)
This compliant solution uses a static inner class to create the singleton instance:This noncompliant code example implements the java.io.Serializable
interface which allows the class to be serializable. Deserialization of the class implies that multiple instances of the singleton can be created.
Code Block | ||
---|---|---|
| ||
class MySingleton implements Serializable { private static finalclass longSingletonHolder serialVersionUID{ = 6825273283542226860L; private static MySingleton INSTANCE; instance = privatenew MySingleton() {; // private 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 any checks to enforce the requirement that the number of instances be limited to one because serialization provides a mechanism to bypass the object's constructor.
Compliant Solution (1) (readResolve
method)
It is recommended that stateful singleton classes be made non-serializable. As a precautionary measure, classes that are serializable must never save a reference to a singleton object in their nontransient or nonstatic instance variables. This prevents the singleton from being indirectly serialized.
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 | ||
---|---|---|
| ||
private Object readResolve() {
return INSTANCE;
}
|
If the serializable singleton class has any other instance fields, they must be declared transient
to be compliant (described later in the nontransient instance fields noncompliant code example).
Compliant Solution (2) (enum
types)
Wiki Markup |
---|
Bloch \[[Bloch 08|AA. Java References#Bloch 08]\] suggests the use of an {{enum}} type as a replacement for traditional implementations. |
Code Block | ||
---|---|---|
| ||
public enum MySingleton {
INSTANCE;
// Other methods
}
|
Functionally, this approach is equivalent to commonplace implementations and is safer. It ensures that only one instance of the object exists at any instant and also provides the serialization property as java.lang.Enum<E>
extends java.io.Serializable
.
Noncompliant Code Example (nontransient instance fields)
This serializable noncompliant code example uses a nontransient instance field str
.
return SingletonHolder.instance;
}
}
|
This approach is known as the initialize-on-demand holder class idiom (see LCK10-J. Use a correct form of the double-checked locking idiom for more information).
Noncompliant Code Example (Serializable)
This noncompliant code example implements the java.io.Serializable
interface, which allows the class to be serialized. Deserialization of the class implies that multiple instances of the singleton can be created.
Code Block | ||
---|---|---|
| ||
class MySingleton implements Serializable {
private static final long serialVersionUID = 6825273283542226860L;
private static MySingleton instance;
private MySingleton() {
// Private 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 once because deserialization can bypass the object's constructor.
Noncompliant Code Example (readResolve()
Method)
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 | ||
---|---|---|
| ||
class MySingleton implements Serializable {
private static final long serialVersionUID = 6825273283542226860L;
private static MySingleton instance;
private MySingleton() {
// Private 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;
}
}
|
At runtime, an attacker can add a class that reads in a crafted serialized stream:
Code Block | ||
---|---|---|
public class Untrusted implements Serializable {
public static MySingleton captured;
public MySingleton capture;
public Untrusted(MySingleton capture) {
this.capture = capture; | ||
Code Block | ||
| ||
class MySingleton implements Serializable { private static final long serialVersionUID = 2787342337386756967L; private static MySingleton INSTANCE; private String[] str = {"one", "two", "three"}; // nontransient instance field private MySingleton() { // private constructor prevents instantiation by untrusted callers } publicprivate void displayStr() { readObject(java.io.ObjectInputStream in) System.out.println(Arrays.toString(str)); } private Object readResolve() { return INSTANCE; } } |
...
|
...
|
...
|
...
throws |
...
Exception |
...
{ |
...
|
...
|
...
in.defaultReadObject();
captured = capture;
}
}
|
The crafted stream can be generated by serializing the following class:
Code Block |
---|
public final class MySingleton
implements java.io.Serializable {
private static final long serialVersionUID =
6825273283542226860L;
public Untrusted untrusted =
new Untrusted(this); // Additional serial field
public MySingleton() { }
}
|
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 nontransient instance field str
:
Code Block | ||
---|---|---|
| ||
class MySingleton implements Serializable {
private static final long serialVersionUID =
2787342337386756967L;
private static MySingleton instance;
// Nontransient instance field
private String[] str = {"one", "two", "three"};
private MySingleton() {
// Private 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 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].
Compliant Solution (Enumeration Types)
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.
Bloch [Bloch 2008] suggests the use of an enumeration type as a replacement for traditional implementations when serializable singletons are indispensable.
Code Block | ||
---|---|---|
| ||
public enum MySingleton {
; // Empty list of enum values
private static MySingleton instance;
// Nontransient field
private String[] str = {"one", "two", "three"};
public void displayStr() {
System.out.println(Arrays.toString(str));
}
}
|
This approach is functionally equivalent to, but much safer than, commonplace implementations. It both ensures that only one instance of the object exists at any instant and provides the serialization property (because java.lang.Enum<E>
extends java.io.Serializable
).
Noncompliant Code Example (Cloneable Singleton)
When the singleton class implements java.lang.Cloneable
directly or through inheritance, it is possible to create a copy of the singleton by cloning it using the object's clone()
method. This noncompliant code example shows a singleton that implements the java.lang.Cloneable
interface.
Code Block | ||
---|---|---|
| ||
class MySingleton implements Cloneable {
private static MySingleton instance;
private MySingleton() {
// Private constructor prevents
// instantiation by untrusted callers
}
// Lazy initialization
public static synchronized MySingleton getInstance() {
if (instance |
Compliant Solution (1) (transient fields)
This compliant solution declares the str
instance field as transient
so that it is not serialized.
Code Block | ||
---|---|---|
| ||
class MySingleton implements Serializable {
// ...
private transient String[] str = {"one", "two", "three"}; // nontransient field
// ...
}
|
Compliant Solution (2) (enum
types, non-transient fields)
This compliant solution uses the enum
type to ensure that only one instance of the singleton exists at any time.
Code Block | ||
---|---|---|
| ||
public enum MySingleton {
INSTANCE;
private String[] str = {"one", "two", "three"}; // nontransient field
public void displayStr() {
System.out.println(Arrays.toString(str));
}
}
|
Noncompliant Code Example (Cloneable singleton)
It is also possible to create a copy of the singleton by cloning it using the object's clone()
method if the singleton class implements java.lang.Cloneable
directly or through inheritance. This noncompliant code example shows a singleton that implements the java.lang.Cloneable
interface.
Code Block | ||
---|---|---|
| ||
class MySingleton implements Cloneable { private static MySingleton INSTANCE; private MySingleton() { // private constructor prevents instantiation by untrusted callers } // Lazy initialization public static synchronized MySingleton getInstance() { if (INSTANCE == null) { INSTANCEinstance = new MySingleton(); } return INSTANCEinstance; } } |
Compliant Solution (
...
Override clone()
...
Method)
Avoid To avoid making the singleton class cloneable by , do not implementing implement the Cloneable
interface or and do not deriving derive from a class that already implements it.
When the singleton class must indirectly implement the Cloneable
interface through inheritance, the object's clone()
method must be overridden with one that throws a CloneNotSupportedException
exception [Daconta 2003] If the singleton class 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
Code Block | ||
---|---|---|
| ||
class MySingleton implements Cloneable { private static MySingleton INSTANCE; private MySingleton() { // private constructor prevents instantiation by untrusted callers } // Lazy initialization public static synchronized MySingleton getInstance() { if (INSTANCE == null Cloneable { private static MySingleton instance; private MySingleton() { // Private INSTANCEconstructor =prevents new MySingleton(); } return INSTANCE; instantiation by untrusted callers } public Object clone() throws CloneNotSupportedException {// Lazy initialization public static throwsynchronized newMySingleton CloneNotSupportedExceptiongetInstance(); { } } |
See MSC05-J. Make sensitive classes noncloneable for more details about restricting the clone()
method.
Noncompliant Code Example (garbage collection)
When the utility of a class is over, it is free to be garbage collected. This behavior can be troublesome when the program needs to maintain only one instance throughout its lifetime.
In this noncompliant code example, when ms1
goes out of scope, it can be garbage collected. Code that is outside the scope can create another instance of the singleton class though the requirement was to use only the original instance.
Code Block | ||
---|---|---|
| ||
{
MySingleton ms1 = MySingleton.getInstance();
// ...
}
MySingleton ms2 = MySingleton.getInstance();
|
This problem can particularly manifest in state bearing singletons.
Compliant Solution (prevent garbage collection)
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 becomes eligible for garbage collection. An easier scheme to prevent the garbage collection is to ensure that there is a direct or indirect reference from a live thread to the singleton object that needs to be preserved. This compliant solution demonstrates this method (based on \[[Patterns 02|AA. Java References#Patterns 02]\]). |
Code Block | ||
---|---|---|
| ||
{
MySingleton ms1 = MySingleton.getInstance();
ObjectPreserver.preserveObject(ms1);
// ...
}
MySingleton ms2 = (MySingleton) ObjectPreserver.getObject();
|
The ObjectPreserver
class is shown below:
Code Block |
---|
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 HashMap<Integer,Object> protectedMap = new HashMap<Integer,Object>();
private ObjectPreserver() {
new Thread(this).start(); // keeps the reference alive
}
public synchronized void run(){
try {
wait();
} catch(InterruptedException e) { /* Forward to handler */ }
}
// Objects passed to this method will be preserved until
// the unpreserveObject method is called
public static void preserveObject(Object obj) {
protectedMap.put(0, obj);
}
// Returns the same instance every time
public static Object getObject() {
return protectedMap.get(0);
}
// Unprotect the objects so that they can be garbage collected
public static void unpreserveObject() {
protectedMap.remove(0);
}
}
|
Risk Assessment
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
|
See OBJ07-J. Sensitive classes must not let themselves be copied for more details about preventing misuse of the clone()
method.
Noncompliant Code Example (Garbage Collection)
A class may be garbage-collected when it is no longer reachable. This behavior can be problematic when the program must maintain the singleton property throughout the entire lifetime of the program.
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 | ||
---|---|---|
| ||
{
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 Java Virtual Machine. This situation typically 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.
Compliant Solution (Prevent Garbage Collection)
This compliant solution takes into account the garbage-collection issue described previously. A class cannot be garbage-collected until the ClassLoader
object used to load it becomes eligible for garbage collection. A simple scheme to prevent garbage collection is to ensure that there is a direct or indirect reference from a live thread to the singleton object that must be preserved.
This compliant solution demonstrates this technique. It prints a consistent hash code across all scopes. It uses the ObjectPreserver
class [Grand 2002] described in TSM02-J. Do not use background threads during class initialization.
Code Block | ||
---|---|---|
| ||
{
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[] { });
ObjectPreserver.preserveObject(singleton); // Preserve the object
System.out.println(singleton.hashCode());
}
ClassLoader cl1 = new MyClassLoader();
Class class1 = cl1.loadClass(MySingleton.class.getName());
Method classMethod =
class1.getDeclaredMethod("getInstance", new Class[] { });
// Retrieve the preserved object
Object singleton = ObjectPreserver.getObject();
System.out.println(singleton.hashCode());
|
Risk Assessment
Using improper forms of the Singleton design pattern may lead to creation of multiple instances of the singleton and violate the expected contract of the classUsing lazy initialization in a Singleton without synchronizing the getInstance()
method may lead to creation of multiple instances and can as a result, violate the expected contract.
Rule | Severity | Likelihood | Remediation Cost |
---|
Priority
Level
CON23- 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/]
\[[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" and Item 77: "For instance control, prefer enum types to readResolve"
\[[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" |
Priority | Level | ||||
---|---|---|---|---|---|
MSC07-J | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
The Checker Framework |
| Linear Checker | Control aliasing and prevent re-use (see Chapter 19) | ||||||
Coverity | 7.5 | SINGLETON_RACE | Implemented | ||||||
Parasoft Jtest |
| CERT.MSC07.ILI | Make lazy initializations thread-safe |
Related Guidelines
Bibliography
Item 3, "Enforce the Singleton Property with a Private Constructor or an | |
Item 15, "Avoiding Singleton Pitfalls" | |
Section 9.10, "Enforcing the Singleton Pattern" | |
[Fox 2001] | |
Singleton | |
Chapter 5, "Creational Patterns," section "Singleton" | |
[JLS 2015] |
...
CON22-J. Do not use incorrect forms of the double-checked locking idiom 11. Concurrency (CON) CON24-J. Use a unique channel to acquire locks on any file