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

Wiki Markup
This noncompliant code example begins initializing the class {{Lazy}}. The code in the {{static}} block is responsible for initialization and starts a background thread which is in a different (anonymous) class. The anonymous class attempts to assign to the {{initialized}} field but has to wait before initialization of the {{Lazy}} class has finished. However, the {{Lazy}} class's main thread invokes the {{join()}} method which waits for the background thread to finish. This interdependency causes a class initialization cycle that results in a deadlock situation. \[[Bloch 05b|AA. Java References#Bloch 05b]\] 

Code Block
bgColor#FFcccc
public class Lazy {
  private static boolean initialized = false;
  static {
    Thread t = new Thread(new Runnable() {
    public void run() {
      initialized = true;
    });
    
    t.start();
    try {
      t.join();
    } catch(InterruptedException ie) {
        throw new AssertionError(ie);
    }
    // Other initialization
  }
  public static void main(String[] args) {
    System.out.println(initialized);
  }
}

Compliant Solution

This compliant solution does not spawn a background thread during class initialization.

Code Block
bgColor#ccccff
public class Lazy {
  private static boolean initialized = false;
  
  static {
    // Other initialization
  }
  
  public static void main(String[] args) {
    System.out.println(initialized);
  }
}

Risk Assessment

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON02 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"

...