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

if (helper == null) {

  synchronized (this) {
    if (helper == null) {
      helper = new Helper();
    }
  }

}
return helper;

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:

helper = new Helper();

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

Comprehensive Categorization: Concurrency

Weaknesses in this category are related to concurrency.

SEI CERT Oracle Secure Coding Standard for Java - Guidelines 09. Locking (LCK)

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.

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.

Weakness Base Elements

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.