The singleton design pattern's intent is succinctly described by the seminal work of Gamma 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 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 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 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 code example uses a nonprivate constructor for instantiating a singleton:
class MySingleton { private static MySingleton instance; protected MySingleton() { instance = new MySingleton(); } public static 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.
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.
class MySingleton { private static final MySingleton instance = new MySingleton(); private MySingleton() { // Private constructor prevents instantiation by untrusted callers } public static MySingleton getInstance() { return instance; } }
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.
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; } }
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, as in this noncompliant code example:
public static MySingleton getInstance() { if (instance == null) { synchronized (MySingleton.class) { instance = new MySingleton(); } } return instance; }
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.
Compliant Solution (Synchronized Method)
To address the issue of multiple threads creating more than one instance of the singleton, make getInstance()
a synchronized method:
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; } }
Compliant Solution (Double-Checked Locking)
Another compliant solution for implementing thread-safe singletons is the correct use of the double-checked locking idiom:
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; } }
This design pattern is often implemented incorrectly (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:
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 (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.
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.
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:
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; } }
The crafted stream can be generated by serializing the following class:
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
:
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.
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.
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; } }
Compliant Solution (Override clone()
Method)
To avoid making the singleton class cloneable, do not implement the Cloneable
interface and do not 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].
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(); } }
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:
{ 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.
{ 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 class.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC07-J | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
The Checker Framework | 2.1.3 | Linear Checker | Control aliasing and prevent re-use (see Chapter 19) |
Coverity | 7.5 | SINGLETON_RACE | Implemented |
Parasoft Jtest | 2024.1 | 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] |
32 Comments
David Svoboda
Looks good so far. Two issues:
Theti Tsiampali
I was not sure if it should be a rule, although singletons are also used to control access to resources and in this sense it could lead to exploitable vulnerability.
OK, I will make it a rule with the code you gave me.
I will also add the relevant link
Thank you
David Svoboda
I meant that MSC05-J should be mentioned in the disuccion, not the Other Languages section. Talk about how it relates to your rule, particularly when you talk about restricting cloning. The Other Languages is for, say, a C++ rule that advocates the same practice your CON33-J rule advocates.
Thomas Hawtin
Because Java initialises classes lazily, there is little need to explicitly write inefficient lazy initialisation code.
If for some reason it is necessary for the instance to be initialised after the containing class is initialised, a nested class can be introduced.
In any case, singletons are inherently dangerous and best avoided if at all possible.
Also there is no need to override clone in a non-subclassable class (and certainly no need to add it to the public API).
Theti Tsiampali
Hi Thomas,
I added the overriding of the clone method because in the case that the MySingleton extends another class that does supports cloning this could lead to a copy, isn't it right?
Regards,
Theti
Thomas Hawtin
If you extend another class then you could have all sorts of methods that you need to override. And that class may evolve. See the mention of java.security.Provider (indirectly) extending Hashtable in the JavaONE antipatterns slides.
Dhruv Mohindra
Since the singleton class is not loaded unless the
getInstance()
method is called (Java's lazy loading), it doesn't make sense to use lazy initialization and delay construction until thenull
check has concluded.Also, there is no need to provide a public final clone() method to block subclasses that strive to create more than one instance of the singleton since the class has a
private
constructor and is thus un-subclassable anyhow (preventing cloning). However, if the superclass of the singleton class implementsCloneable
then it may need to be overridden to throw aCLoneNotSupportedException
as shown. Note that in the latter case, the class probably ceases to be a singleton as singletons are not expected to implementCloneable
.Though this rule has some useful information, it doesn't do justice to its name. I think 'Avoid singleton pitfalls' or something more general might be more useful. The compliant solution could be just the proper way to construct a singleton. Awaiting comments.
Thomas Hawtin
Josh Bloch suggests using single-element enums:
I suggest avoiding (stateful) singletons.
David Svoboda
Well, right now we don't have any other wisdom pertaining to
singletons. Offhand, we might have a rule advising preventing
singletons from being cloned, for instance. I am curious why
Mr. Hawtin considers singletons dangerous; it sounds like we should
indicate why in this rule. To sum up, let's collect what we know about
singletons before deciding how to adjust this rule.
Dhruv Mohindra
Tentatively, I have renamed the rule as it contained not just the getInstance() discussion but several other things as well. I have also added some discussion about serialization dangers and garbage collection issues.
Robert Seacord (Manager)
Can't generate PDF for this rule for some reason.
Dhruv Mohindra
Removed some '. . .' sequences. Might work now.
David Svoboda
First of all, the material in this rule is good. Most of it needs no fixing.
FTM why would a singleton class NOT maintain its own private static copy? This code sample is trying to 'enforce singleton-ness' on a class that clearly was not designed to be a singleton. Perhaps the ObjectPreserver class works as suggested, but its complex. I think if I had to enforce singleton-ness on a class I would make a singleton wrapper class wround it. (That wouldn't prevent others from creating multiple instances, but if the class was not private, there's little I can do then.)
Dhruv Mohindra
static
object to get garbage collected when its classloader is garbage collected. This is more of a concern when a class is loaded using a custom class loader instead of standard ones. I could add this information. I also don't think that the NCE assumes nonstatic singletons.Can you possibly demonstrate your wrapper class around the singleton? How is it useful if it allows creation of multiple instances?
private
constructor (this is could be an exception to TSM01-J. Do not let the (this) reference escape during object construction). If you think otherwise, can you share your reasoning about the insecurity? (it appears that the JMM guarantees might be violated, I am investigating this)Dhruv Mohindra
Regarding my last bullet, from [Goetz 06] section 3.2 Publication and Escape:
I am not sure that we are publishing
this
to anyone except the thread (and we are allowing the thread to see the class in a partially initialized state because the only purpose of the thread is to keep the reference alive). There is also no need to declare the class final because it has aprivate
constructor.David Svoboda
Having studied CON03-J further, I think my solution to the ObjectPreserver is safe, even though it does technically violate CON03-J. This is simply because the ObjectPreserver doesn't actually access any local fields during its background thread, so no deadlock occurs. It still is a violation of CON03-J, with the solutions being to either eliminate the background thread or start it in a method call that gets invoked after the ObjectPreserver is initialized. I'm not sure the purpose of the background thread anyway, since it waits forever. I think there are better ways to keep the ObjectPreserver itself from getting garbage-collected, if that's the reason.
BTW assuming we want ObjectPreserver to start its background thread, the thread should be marked as a daemon thread via
Thread.setDaemon(true)
.Dhruv Mohindra
I agree that currently it is a violation of CON03 (starting background threads during class initialization) and CON14 (letting
this
escape by starting the thread in the constructor).However, this example does not appear to be unsafe. When this happens, my thinking is that it is an exception. IOW, wrt:
this
escapes, nothing bad can happen (HashMap is statically initialized so is immune from any problems wrt partial initialization and so on whenthis
escapes). This means thatthis
can be allowed to escape when all fields are being "eagerly" initialized. (possibly an exception to CON14)This is to prevent garbage collection; a thread always refers to the object. The JVM does not exit until all threads have finished executing.
It might be a good idea to make this a daemon thread so that the JVM can exit without waiting for this new thread to finish. From my understanding, as long as the JVM is up, this object will not be garbage collected.
Thomas Hawtin
The readResolve solution does not work. For instance, the serialised form (which need not match the loaded class form to allow adding and removing of fields) may contain back-references which are deserialised before readResolve is called, and therefore see the original object.
Unrelatedly, I'd like to point out the overly narrow "OBJ03-J. Do not use public static non-final variables". Where you have a (mutable) singleton you have the same problems. Singletons only provide obfuscation.
Dhruv Mohindra
Is it also unsafe to use the
readResolve()
approach when all instance fields aretransient
?I note your point regarding mutable singletons and I think the current guideline does not recommend them.
Thomas Hawtin
The serialisation format is very flexible. The fields stored in the stream needn't be the same as that in the object. Fields can be both added and removed. So whether all the fields are transient or not is irrelevant.
Dhruv Mohindra
If the singleton has only nontransient fields, what would you replace in the byte stream to force the mechanism to deserialize the crafted class first? The idea being that the crafted class steals a reference to an instance of the partially reconstructed singleton and stores it in some accessible static field. How/where do you insert these back-references in the serialized form so that they are deserialized first before
readResolve()
is called? Can one introduce some form of an inner class in the serialized form to carry out such an attack? Thanks!Thomas Hawtin
There is nothing magic about inner classes as far as the JVM and java serialisation are concerned. They just have funny names and attributes for reflection.
Consider a serialisable singleton:
At deserialisation (and serialisation) time we are going to add a class to attack that.
In order to avoid having to create the serialised byte stream by hand (not a pleasant exercise, I can tell you), we can create the byte data on our own machine by substituting a modified version of the attacked class.
On deserialisation, the serial field MySingleton.captchor is deserialised before MySingleton.readResolve is called. So the instance assigned to Captchor.captured is not MySingleton.INSTANCE.
Dhruv Mohindra
Thanks a bunch - that really helps. The only missing piece now is: if we add the untrusted
Captchor
class during (de)serialization, how do we get trusted code to read the spurious singleton from the public static fieldcaptured
of the untrusted classCaptchor
? So to exploit this, should there be another vulnerability in the trusted code? Or do we assume that someone creating the singleton has evil intentions (otherwise a friendly programmer)?EDIT: Another quick question: if you deserialize a class with an inner class - is the inner class deserialized first? I can't seem to find this in the documentation. The closest I have is SER06-J. Do not serialize instances of inner classes but I was thinking attack code might be able to use/violate this to exploit the singleton in some way.
Dhruv Mohindra
Yozo,
Regarding your last change:
I fear the original sentence was ok.
Yozo TODA
do you mean, as the original sentence, "serialization can bypass the object's constructor" ?
my understanding is that constructors may work for DEserialization (not serialization), and that bypassing the constructor is a problem because an object is created to the memory space without the constructor's check.
and one more, I should have wrote that comment as
let me know if I'm misunderstanding anything...
David Svoboda
I agree with Yozo-san. IIRC the sentence used 'Serialization' simply because it was referring to both serialization & deserialization. Changing it to 'deserialization' made it more precise.
Dhruv Mohindra
I appreciate the current change. Earlier I had only read the ambiguous review comment which Yozo san has corrected above.
Masaki Kubo
Compliant Solution (Enumeration Types) has no actual enumeration. (Is this code taken from Bloch 2008?)
David Svoboda
I added a trivial list of enum values to the code.
James Ahlborn
the "CS (Prevent Garbage Collection)" is kind of confusing as the second chunk of code (outside the block) contains some ClassLoader related stuff which is never actually used (ObjectPreserver is used to retrieve the original reference). if you were to use the second classloader, you would, of course, still get a new, different reference. what would be perhaps more interesting is if the MySingleton class itself used the ObjectPreserver internally (inside the
getInstance()
method), as this would show that subsequent ClassLoaders would all see the first instance.as a side note, this example hinges on the ObjectPreserver itself being available from the parent ClassLoader. were it included in the nested ClassLoaders, you wouldn't get the same instance in the second call (that instance would still exist, you just wouldn't be able to retrieve it).
A Bishop
Variable Instance should be instance (and INSTANCE when static final) (Violates standard java naming convention)
Also, the lazy initialization of the singleton instance is what causes most of the other issues discussed. I struggle to see any need for lazy initialization of a singleton. Maybe if using a container that is reflectively loading the class for a service provider type pattern? Even in that case you'd think it would be better to refactor into a service provider into a service provider that uses a singleton.
David Svoboda
I s/Instance/instance/g; for private static variables. (Upcased var names are only conventional for public static final variables.)
I agree that avoiding lazy initialization prevents many of these problems. The first compliant solution initializes statically (that is, when the class is first loaded). There are several reasons that warrant lazy initialization, such as if you must begin main() before initializing your singleton. Lazy initialization can also help prevent initialization cycles, which are forbidden by DCL00-J. Prevent class initialization cycles.