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

Compare with Current View Page History

« Previous Version 48 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 underway. [[Bloch 05b]]

Noncompliant Code Example

This noncompliant code example begins initializing the class Lazy.

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

The code in the static block is responsible for initialization, and starts a background thread. The background thread attempts to assign to the field number but needs to wait until initialization of the Lazy class has finished.

Recall 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 information). Consequently, the background thread must wait for the foreground thread to finish initialization before it can 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 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.

public class Lazy {
  private static boolean flag;

  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) {
          flag = false;
          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.

Exceptions

CON03:EX1: The ObjectPreserver class (based on [[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.

public final class ObjectPreserver implements Runnable {
  private static ObjectPreserver lifeLine = new ObjectPreserver();

  private ObjectPreserver() {
    Thread thread = new Thread(this);
    thread.setDaemon(true);
    thread.start(); // keep this object alive
  }
 
  // Neither this class, nor HashSet will be garbage collected.
  // References from HashMap to other objects will also exhibit this property
  private static final ConcurrentHashMap<Integer,Object> protectedMap 
    = new ConcurrentHashMap<Integer,Object>();
  
  public synchronized void run() {
    try {
      wait();
    } catch(InterruptedException e) { 
      // Forward to handler
      Thread.currentThread().interrupt(); // Reset interrupted status 
    }
  }

  // Objects passed to this method will be preserved until
  // the unpreserveObject method is called
  public static void preserveObject(Object obj) {    
    protectedMap.put(0, obj);  
  }
  
  // Returns the same instance every time
  public static Object getObject() {
    return protectedMap.get(0);	  
  }
  
  // Unprotect the objects so that they can be garbage collected
  public static void unpreserveObject() {
    protectedMap.remove(0);
  }
}

This is a singleton class (see CON23-J. Address the shortcomings of the Singleton design pattern for how to properly handle singleton classes). The initialization creates a background thread referencing the object, and the thread itself waits forever. Consequently this object exists for the remainder of the JVM's lifetime; however, as it is managed by a daemon thread, the thread (and object) will not hinder a normal shutdown of the JVM.

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

[[Bloch 05b]] 8. "Lazy Initialization"
[[Patterns 02]] Chapter 5, Creational Patterns, Singleton


CON02-J. Always synchronize on the appropriate object      11. Concurrency (CON)      CON04-J. Synchronize using an internal private final lock object

  • No labels