Versions Compared

Key

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

Wiki Markup
Starting and using background threads during class initialization can result in class initialization cycles and eventually, deadlock. This is because the main thread responsible for performing class initialization may block waiting for the background thread, which in turn will wait for the main thread to finish class initialization. This issue can arise, for example, when a database connection is established in a background thread while class initialization is in progress. \[[Bloch 05b|AA. Java References#Bloch 05b]\] 

Noncompliant Code Example

This noncompliant code example begins initializing the class Lazy.

...

Similar to this noncompliant code example, threads should not be started from constructors. See CON14-J. Do not let the "this" reference escape during object construction for more information.

Compliant Solution (static initializer, no background threads)

This compliant solution also uses a static initializer but does not spawn a background thread from it.

Code Block
bgColor#ccccff
public class Lazy {
  private static int number;
  
  static {
    // Initialize, for example, a database connection
    this.number = 42;
  }
  
  public static void main(String[] args) {
    System.out.println(number);
  }
}

Compliant Solution (ThreadLocal)

This compliant solution uses a ThreadLocal object to initialize a database connection and sets flag to true depending on whether the initialization succeeds.

...

It is safe to set shared class variables from the initialValue() method. Consequently, each thread will see a consistent value of the flag field.

Exceptions

Wiki Markup
*CON03:EX1*: The {{ObjectPreserver}} class (based on \[[Patterns 02|AA. Java References#Patterns 02]\]) is shown below: This class provides a mechanism for storing object references, which prevents an object from being garbage-collected, even if the remaining program no longer maintains a reference to the object.

...

While the initialization does involve a background thread, the background thread accesses no fields and so creates no deadlock. Consequently this code is a safe and useful exception to this rule.

Risk Assessment

Starting and using background threads during class initialization can result in deadlock conditions.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON03- J

low

likely

high

P3

L3

Automated Detection

TODO

Related Vulnerabilities

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

References

Wiki Markup
\[[Bloch 05b|AA. Java References#Bloch 05b]\] 8. "Lazy Initialization"
\[[Patterns 02|AA. Java References#Patterns 02]\] Chapter 5, Creational Patterns, Singleton

...