Double-Checked Locking
The product uses double-checked locking to access a resource without the overhead of explicit synchronization, but the locking is insufficient.
Description
Double-checked locking refers to the situation where a programmer checks to see if a resource has been initialized, grabs a lock, checks again to see if the resource has been initialized, and then performs the initialization if it has not occurred yet. This should not be done, as it is not guaranteed to work in all languages and on all architectures. In summary, other threads may not be operating inside the synchronous block and are not guaranteed to see the operations execute in the same order as they would appear inside the synchronous block.
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
It may seem that the following bit of code achieves thread safety while avoiding unnecessary synchronization...
The programmer wants to guarantee that only one Helper() object is ever allocated, but does not want to pay the cost of synchronization every time this code is called.
Suppose that helper is not initialized. Then, thread A sees that helper==null and enters the synchronized block and begins to execute:
If a second thread, thread B, takes over in the middle of this call and helper has not finished running the constructor, then thread B may make calls on helper while its fields hold incorrect values.
See Also
Weaknesses in this category are related to concurrency.
Weaknesses in this category are related to the rules and recommendations in the Locking (LCK) section of the SEI CERT Oracle Secure Coding Standard for Java.
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) displays only weakness base elements.
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.