...
The
...
singleton
...
design
...
pattern's
...
intent
...
is
...
succinctly
...
described
...
by
...
the
...
seminal
...
work
...
of
...
Gamma
...
et
...
al.
...
...
...
]:
Ensure a class only has one instance, and provide a global point of access to it.
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, system monitoring and logging, implementing printer spoolers, or even 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 uses a single instance of a class that encloses a private static 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.
A class that implements the singleton design pattern must prevent multiple instantiations. Relevant techniques include
- making its constructor private.
- employing lock mechanisms to prevent an initialization routine from running 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 (Non-private Constructor)
This noncompliant code example uses a non-private constructor for instantiating a singleton.
Code Block | ||
---|---|---|
| ||
\]: {quote} Ensure a class only has one instance, and provide a global point of access to it. {quote} 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|AA. References#Fox 01]\]. Other applications of singletons involve maintaining performance statistics, system monitoring and logging, implementing printer spoolers, or even 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 uses a single instance of a class that encloses a private static 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. A class that implements the singleton design pattern must prevent multiple instantiations. Relevant techniques include * making its constructor private. * employing lock mechanisms to prevent an initialization routine from running 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. h2. Noncompliant Code Example (Non-private Constructor) This noncompliant code example uses a non-private constructor for instantiating a singleton. {code:bgColor=#FFcccc} class MySingleton { private static MySingleton Instance; protected MySingleton() { Instance = new MySingleton(); } public static synchronized MySingleton getInstance() { return Instance; } } {code} |
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.
...
Compliant
...
Solution
...
(Private
...
Constructor)
...
This
...
compliant
...
solution
...
reduces
...
the
...
accessibility
...
of
...
the
...
constructor
...
to
...
private
...
and
...
immediately
...
initializes
...
the
...
field
...
Instance
...
,
...
allowing
...
it
...
to
...
be
...
declared
...
final.
...
Singleton
...
constructors
...
must
...
be
...
private.
Code Block | ||||
---|---|---|---|---|
| =
| |||
} class MySingleton { private static final MySingleton Instance = new MySingleton(); private MySingleton() { // private constructor prevents instantiation by untrusted callers } public static synchronized MySingleton getInstance() { return Instance; } } {code} The {{MySingleton}} class need not be declared final because it has a private constructor. h2. Noncompliant Code Example (Visibility across Threads) Multiple instances of the {{Singleton}} |
The MySingleton
class need not be declared final because it has a private constructor.
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 | ||
---|---|---|
| ||
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:bgColor=#FFcccc} class MySingleton { private static MySingleton Instance; private MySingleton() { // private constructor prevents instantiation by untrusted callers } // Lazy initialization public static MySingleton getInstance() { // Not synchronized if (Instance == null) { Instance = new MySingleton(); } return Instance; } } {code} |
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
...
when
...
the
...
singleton
...
construction
...
is
...
encapsulated
...
in
...
a
...
synchronized
...
block.
Code Block | ||||
---|---|---|---|---|
| =
| |||
} public static MySingleton getInstance() { if (Instance == null) { synchronized (MySingleton.class) { Instance = new MySingleton(); } } return Instance; } {code} |
This
...
is
...
because
...
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.
...
Compliant Solution (Synchronized
...
Method)
...
To
...
address
...
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 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; } } {code} h2. Compliant Solution |
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 | ||
---|---|---|
| ||
{code:bgColor=#ccccff} class MySingleton { private static volatile MySingleton Instance; private MySingleton() { // private 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; } } {code} |
This
...
design
...
pattern
...
is
...
often
...
implemented
...
incorrectly.
...
Refer
...
to
...
rule
...
...
...
...
...
...
...
...
...
...
...
...
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 | ||||
---|---|---|---|---|
| =
| |||
} class MySingleton { static class SingletonHolder { static MySingleton Instance = new MySingleton(); } public static MySingleton getInstance() { return SingletonHolder.Instance; } } {code} |
This
...
is
...
known
...
as
...
the
...
initialize-on-demand
...
holder
...
class
...
idiom.
...
Refer
...
to
...
rule
...
...
...
...
...
...
...
...
...
...
...
...
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; } } {code} |
A
...
singleton's
...
constructor
...
cannot
...
install
...
checks
...
to
...
enforce
...
the
...
requirement
...
that
...
the
...
class
...
is
...
only
...
instantiated
...
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
...
is
...
insecure
...
even
...
when
...
all
...
the
...
fields
...
are
...
declared
...
transient
...
or
...
static.
Code Block | ||
---|---|---|
| ||
{code:bgColor=#FFcccc} 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; } } {code} At |
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; } private void readObject(java.io.ObjectInputStream in) throws Exception { in.defaultReadObject(); captured = capture; } } {code} The crafted stream |
The crafted stream can be generated by serializing the following class:
Code Block |
---|
can be generated by serializing the following class: {code} 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() { } } {code} |
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
...
(Non-transient
...
Instance
...
Fields)
...
This
...
serializable
...
noncompliant
...
code
...
example
...
uses
...
a
...
non-transient
...
instance
...
field
...
str
...
.
Code Block | ||||
---|---|---|---|---|
| =
| |||
} class MySingleton implements Serializable { private static final long serialVersionUID = 2787342337386756967L; private static MySingleton Instance; // non-transient 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; } } {code} |
"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"
...
[
...
...
...
]
...
.
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
...
prevents
...
the
...
singleton
...
from
...
being
...
indirectly
...
serialized.
...
Bloch
...
[
...
...
...
]
...
suggests
...
the
...
use
...
of
...
an
...
enumeration
...
type
...
as
...
a
...
replacement
...
for
...
traditional
...
implementations
...
when
...
serializable
...
singletons
...
are
...
indispensable.
Code Block | ||
---|---|---|
| ||
{code:bgColor=#ccccff} public enum MySingleton { ; // empty list of enum values private static MySingleton Instance; // non-transient field private String[] str = {"one", "two", "three"}; public void displayStr() { System.out.println(Arrays.toString(str)); } } {code} |
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 == null) { Instance = new MySingleton(); } return Instance; } } {code} h2. Compliant Solution (Override {{ |
Compliant Solution (Override clone()
...
Method)
...
Avoid
...
making
...
the
...
singleton
...
class
...
cloneable
...
by
...
not
...
implementing
...
the Cloneable
interface and not deriving 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].
Code Block | ||
---|---|---|
| ||
{{Cloneable}} interface and not deriving 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|AA. References#Daconta 03]\]. {code:bgColor=#ccccff} 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) { Instance = new MySingleton(); } return Instance; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } {code} |
See
...
rule
...
...
...
...
...
...
...
...
...
...
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 | ||
---|---|---|
| ||
{code: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} {mc} |
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 JVM. This typically happens 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 rule 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(); back-up code { ClassLoader cl1 = new FirstClassLoader(); Class class1 = cl1.loadClass(MySingleton.class.getName()); Method instanceMethod = class1.getDeclaredMethod("getInstance", new Class[] { }); Object singleton = instanceMethod.invoke(null, new Object[] { } ); } ClassLoader cl2 = new SecondClassLoader(); Class class2 = cl2.loadClass(MySingleton.class.getName()); Method instanceMethod = class2.getDeclaredMethod("getInstance", new Class[] { }); Object singleton = instanceMethod.invoke(null, new Object[] { } ); {mc} 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. {mc} // The following class produces the same hash code from different scopes, so is safe public class StaticClass { public void doSomething() { { MySingleton ms = new MySingleton(); Object singleton = ms.getInstance(); System.out.println(singleton.hashCode()); } MySingleton ms = new MySingleton(); Object singleton = ms.getInstance(); System.out.println(singleton.hashCode()); } public static void main(String[] args) { StaticClass sc = new StaticClass(); sc.doSomething(); } } {mc} 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 JVM. This typically happens 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. h2. 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|AA. References#Grand 02]\] described in rule [TSM02-J. Do not use background threads during class initialization]. {code:bgColor=#ccccff} { 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()); {code} h2. 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 class. || Rule || Severity || Likelihood || Remediation Cost || Priority || Level || | MSC07-J | low | unlikely | medium | {color:green}{*}P2{*}{color} | {color:green}{*}L3{*}{color} | h2. Related Guidelines | [MITRE CWE|http://cwe.mitre.org/] | [CWE-543|http://cwe.mitre.org/data/definitions/543.html]. Use of Singleton pattern without synchronization in a multithreaded context | h2. Bibliography | \[[Bloch 2008|AA. 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}} | | \[[Daconta 2003|AA. References#Daconta 03]\] | Item 15. Avoiding singleton pitfalls | | \[[Darwin 2004|AA. References#Darwin 04]\] | 9.10 Enforcing the Singleton Pattern | | \[[Fox 2001|AA. References#Fox 01]\] | [When Is a Singleton Not a Singleton?|http://java.sun.com/developer/technicalArticles/Programming/singletons/] | | \[[Gamma 1995|AA. References#Gamma 95]\] | Singleton | | \[[Grand 2002|AA. References#Grand 02]\] | Chapter 5, Creational Patterns, Singleton | | \[[JLS 2005|AA. References#JLS 05]\] | [Chapter 17, Threads and Locks|http://java.sun.com/docs/books/jls/third_edition/html/memory.html] | ---- [!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|MSC06-J. Do not modify the underlying collection when an iteration is in progress] [!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|49. Miscellaneous (MSC)] |
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 class.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC07-J | low | unlikely | medium | P2 | L3 |
Related Guidelines
Bibliography
Item 3. Enforce the singleton property with a private constructor or an enum type; and Item 77. For instance control, prefer enum types to | |
Item 15. Avoiding singleton pitfalls | |
9.10 Enforcing the Singleton Pattern | |
[Fox 2001] | |
Singleton | |
Chapter 5, Creational Patterns, Singleton | |
[JLS 2005] |
...