Use of Singleton Pattern Without Synchronization in a Multithreaded Context
The product uses the singleton pattern when creating a resource within a multithreaded environment.
The use of a singleton pattern may not be thread-safe.
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.
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.
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.
Weaknesses in this category are related to concurrency.
This category identifies Software Fault Patterns (SFPs) within the Missing Lock cluster (SFP19).
This view (slice) covers all the elements in CWE.
This view (slice) lists weaknesses that can be introduced during implementation.
This view (slice) covers issues that are found in Java programs that are not common to all languages.