CWE
Home > CWE List > CWE- Individual Dictionary Definition (1.1)  
Search by ID:

CWE-543: Use of Singleton Pattern in a Non-thread-safe Manner

Individual Definition in a New Window
Use of Singleton Pattern in a Non-thread-safe Manner
Status: Incomplete
Weakness ID: 543 (Weakness Variant)
Description
Summary

The use of a singleton pattern may not be thread-safe.

Potential Mitigations

Use Thread-Specific Storage Pattern

In multithreading environments, storing user data in Servlet member fields introduces a data access race condition. Do not use member fields to store information in the Servlet.

Demonstrative Examples

This method is part of a singleton pattern, yet the following singleton() pattern is not thread-safe. It fails to ensure the creation of only one object.

Java Example:
private static NumberConverter singleton;
public static NumberConverter get_singleton() {
if (singleton == null) singleton = new NumberConverter();
return singleton;
}

Consider the following course of events: Thread A enters the method, finds singleton to be null, begins the NumberConverter constructor, and then is swapped out of execution. Thread B enters the method and finds that singleton remains null. This will happen if A was swapped out during the middle of the constructor, for the object reference is not set to point at the new object on the heap until the object is fully initialized. Thread B continues and constructs another NumberConverter object and returns it while exiting the method. Thread A continues, finishes constructing its NumberConverter object, and returns its version. It created and returned two different objects. Many programmers turned to the double-check pattern to avoid the overhead of a synchronized call, which is an extension of the one employed, until it too was shown to be not thread-safe.

Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness BaseWeakness Base662Insufficient Synchronization
Research Concepts (primary)1000
ChildOfWeakness VariantWeakness VariantWeakness Variant383J2EE Bad Practices: Direct Use of Threads
Development Concepts (primary)699
Taxonomy Mappings
Mapped Taxonomy Name
Anonymous Tool Vendor (under NDA)
Applicable Platforms
Languages
Java
Time of Introduction
* Implementation
Content History
Submissions
Anonymous Tool Vendor (under NDA). (Externally Mined)
Modifications
Eric Dalci. Cigital. 2008-07-01. (External)
updated Potential_Mitigations, Time_of_Introduction
CWE Content Team. MITRE. 2008-09-08. (Internal)
updated Relationships, Taxonomy_Mappings
Page Last Updated: November 24, 2008