Use of Singleton Pattern Without Synchronization in a Multithreaded Context

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


Description

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

Demonstrations

The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.

Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.

Example One

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.

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, 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.

See Also

Comprehensive Categorization: Concurrency

Weaknesses in this category are related to concurrency.

SFP Secondary Cluster: Missing Lock

This category identifies Software Fault Patterns (SFPs) within the Missing Lock cluster (SFP19).

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

Weaknesses Introduced During Implementation

This view (slice) lists weaknesses that can be introduced during implementation.

Weaknesses in Software Written in Java

This view (slice) covers issues that are found in Java programs that are not common to all languages.


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.