Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
// Correct multithreaded version using synchronization
final class Foo { 
  private Helper helper = null;
  
  public synchronized Helper getHelper() {
    if (helper == null) {
      helper = new Helper();
    }
    return helper;
  }
  // ...
}

The double-checked locking idiom is used to provide lazy initialization in multithreaded code. In a multithreading scenario, traditional lazy initialization is supplemented by reducing the cost of synchronization for each method access by limiting the improves performance by limiting synchronization to the rare case where the instance is required to be created of new instance creation and forgoing it when during the common case of retrieving an already created instance.

Noncompliant Code Example

The double-checked locking pattern uses block synchronization instead of method synchronization. It strives to make the previous code example faster by ; installing an additional null check before attempting synchronization. This makes a potentially expensive synchronization necessary only for initialization, and dispensable for the common case of retrieving the value of helper. The noncompliant code example shows the originally proposed DCL pattern.

Noncompliant Code Example

This noncompliant code example uses the incorrect form of the double checked locking idiom.

...