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.

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"

...