Versions Compared

Key

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

Wiki Markup
The usual way of initializing an object is to use a constructor. Sometimes it is required to limit the number of instances of the sub-object to just one (this is similar to a singleton, however, the sub-object may or may not be {{static}}). In addition, a technique called lazy initialization is used to defer the construction of the sub-object until it is actually required. Reasons for doing so include optimization and breaking harmful circularities in class and instance initialization \[[Bloch 05|AA. Java References#Bloch 05]\].

For these purposes, instead of a constructor, a class or an instance method should be used for initialization, depending on whether the sub-object is static or not. The method checks whether the instance has already been created and if not, creates it. If the instance already exists, it simply returns it. This is shown below:

...

In a multi-threading scenario, the initialization must be synchronized so that two or more threads do not create multiple instances of the sub-object. The code shown below is correctly synchronizedsafe for execution in a multithreaded environment, albeit slower than the previous, single threaded code example.

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

The double checked locking (DCL) idiom is sometimes used to provide lazy initialization in multithreaded code. In a multi-threading scenario, lazy initialization is supplemented by reducing the cost of synchronization on each method access by limiting the synchronization to the case where the instance is to be created and forgoing it when retrieving an already created instance.

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

According to the Java Memory Model (discussion reference) \[[Pugh 04|AA. Java References#Pugh 04]\]:

... writes that initialize the Helper object and the write to the helper field can be done or perceived out of order. As 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.

This makes the originally proposed double-checked locking pattern insecure.

The rule CON26-J. Do not publish partially-constructed objects discusses further the possibility of a non-null reference to a helper object with default values for fields in the helper object.

Noncompliant Code Example

...

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

Wiki Markup
According to the Java Memory Model (discussion reference) \[[Pugh 04|AA. Java References#Pugh 04]\]:

... writes that initialize the Helper object and the write to the helper field can be done or perceived out of order. As 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.

This makes the originally proposed double-checked locking pattern insecure. The rule CON26-J. Do not publish partially-constructed objects discusses further the possibility of a non-null reference to a helper object that observes default values for fields in the helper object.

Compliant Solution (volatile)

This compliant solution declares the Helper object as volatile and consequently, uses the correct form of the double-check locking idiom.

...

Note that if Foo was mutable, the Helper field would need to be declared volatile as shown in CON00-J. Declare shared variables as volatile to ensure visibility and prevent reordering of statements. Also, the method getHelper() is an instance method and the accessibility of the helper field is private. This allows safe publication of the Helper object, in that, a thread cannot observe a partially initialized Foo object (CON26-J. Do not publish partially-constructed objects).

Compliant Solution (static initialization)

...

Variables declared static are guaranteed to be initialized and made visible to other threads immediately. Static initializers also exhibit these properties. This approach should not be confused with eager initialization because in this case, the Java Language Specification guarantees lazy initialization of the class when it will be is first used.

Compliant Solution (initialize-on-demand holder class idiom)

...

Wiki Markup
\[[API 06|AA. Java References#API 06]\] 
\[[Pugh 04|AA. Java References#Pugh 04]\]
\[[Bloch 01|AA. Java References#Bloch 01]\] Item 48: "Synchronize access to shared mutable data"
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 71: "Use lazy initialization judiciously"
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 609|http://cwe.mitre.org/data/definitions/609.html] "Double-Checked Locking"

...