CWE-543 在多线程上下文中使用缺失同步机制的Singleton设计模式

Use of Singleton Pattern Without Synchronization in a Multithreaded Context

结构: Simple

Abstraction: Variant

状态: Incomplete

被利用可能性: unkown

基本描述

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

扩展描述

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

相关缺陷

  • cwe_Nature: ChildOf cwe_CWE_ID: 820 cwe_View_ID: 1000 cwe_Ordinal: Primary

  • cwe_Nature: ChildOf cwe_CWE_ID: 820 cwe_View_ID: 699 cwe_Ordinal: Primary

适用平台

Language: [{'cwe_Name': 'Java', 'cwe_Prevalence': 'Undetermined'}, {'cwe_Name': 'C++', 'cwe_Prevalence': 'Undetermined'}]

常见的影响

范围 影响 注释
['Other', 'Integrity'] ['Other', 'Modify Application Data']

可能的缓解方案

Architecture and Design

策略:

Use the Thread-Specific Storage Pattern. See References.

Implementation

策略:

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

Implementation

策略:

Avoid using the double-checked locking pattern in language versions that cannot guarantee thread safety. This pattern may be used to avoid the overhead of a synchronized call, but in certain versions of Java (for example), this has been shown to be unsafe because it still introduces a race condition (CWE-209).

示例代码

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.

bad Java

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

Consider the following course of events:

None

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

分类映射

映射的分类名 ImNode ID Fit Mapped Node Name
The CERT Oracle Secure Coding Standard for Java (2011) MSC07-J Prevent multiple instantiations of singleton objects
Software Fault Patterns SFP19 Missing Lock

引用