You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 32 Next »

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]]

Noncompliant Code Example

This noncompliant code example begins initializing the class Lazy.

public class Lazy {
  private static boolean flag = false;
  static {
    Thread t = new Thread(new Runnable() {
      public void run() {
        // Initialize, for example, a database connection
        flag = true;
      }
    });
    
    t.start();
    try {
      t.join();
    } catch(InterruptedException ie) {
        throw new AssertionError(ie);
    }
    // Other initialization
  }
  public static void main(String[] args) {
    System.out.println(flag);
  }
}

The code in the static block is responsible for initialization, and starts a background thread. The background thread attempts to assign to the flag but needs to wait before initialization of the Lazy class has finished. Remember that statically-initialized fields are guaranteed to be fully constructed before becoming visible to other threads (see [CON26-J. Do not publish partially initialized objects] for more info). Consequently the background thread must wait for the foreground thread to finish initialization before it may proceed. 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]]

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.

public class Lazy {
  private static boolean flag = false;
  
  static {
    // Initialize, for example, a database connection
    flag = true;
  }
  
  public static void main(String[] args) {
    System.out.println(flag);
  }
}

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.

public class Lazy {
  private static boolean flag = false;  

  private static final ThreadLocal<Connection> connectionHolder
    = new ThreadLocal<Connection>() {
      public Connection initialValue() {
        try {
          Connection conn = DriverManager.getConnection("connectionstring");
          flag = true;
          return conn;
        } catch (SQLException e) {
          return null;
        }
      }
    };
    
  public static Connection getConnection() {
    return connectionHolder.get();
  }

  public static void main(String[] args) {
    Connection conn = getConnection();
    System.out.println(flag);
  }
}

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

[[Bloch 05b]] 8. "Lazy Initialization"


CON02-J. Always synchronize on the appropriate object      11. Concurrency (CON)      CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism

  • No labels