Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

... writes that initialize the Helper object and the write to the helper field can be done or perceived out of order. ThusAs a result, a thread which invokes getHelper() could see a non-null reference to a helper object, but see the default values for fields of the helper object, rather than the values set in the constructor.

Even if the compiler does not reorder those writes, on a multiprocessor the processor or the memory system may reorder those writes, as perceived by a thread running on another processor.

...

Code Block
bgColor#FFCCCC
// ""Double-Checked Locking"" idiom
class Foo { 
  private Helper helper = null;
  public Helper getHelper() {
    if (helper == null) { 
      synchronized(this) {
        if (helper == null) 
          helper = new Helper();
      }    
    }
    return helper;
  }
  // other functions and members...
}

...

EX1: Explicitly synchronized code does not require the use of double-checked locking.

Wiki Markup
*EX2:* ""Although the double-checked locking idiom cannot be used for references to objects, it can work for 32-bit primitive values (e.g., int's or float's). Note that it does not work for long's or double's, since unsynchronized reads/writes of 64-bit primitives are not guaranteed to be atomic."" \[[Pugh 04|AA. Java References#Pugh 04]\]

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] 
\[[Pugh 04|AA. Java References#Pugh 04]\]
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 609|http://cwe.mitre.org/data/definitions/609.html] ""Double-Checked Locking""

...

FIO36-J. Do not create multiple buffered wrappers on an InputStream            09. Input Output (FIO)            09. Input Output (FIO)