CWE-543: Use of Singleton Pattern Without Synchronization in a Multithreaded Context

Description

The product uses the singleton pattern when creating a resource within a multithreaded environment.

Submission Date :

July 19, 2006, midnight

Modification Date :

2023-06-29 00:00:00+00:00

Organization :

MITRE
Extended Description

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

Example Vulnerable Codes

Example - 1

This method is part of a singleton pattern, yet the following singleton() pattern is not thread-safe. It is possible that the method will create two objects instead of only one.


singleton = new NumberConverter();
if (singleton == null) {}return singleton;private static NumberConverter singleton;public static NumberConverter get_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, because 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.

At this point, the threads have created and returned two different objects.

Related Weaknesses

This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.

Visit http://cwe.mitre.org/ for more details.