Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: made a few textual edits based on comments
Wiki Markup
Starting and using background threads during class initialization can result in class initialization cycles and 

...

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 

...

during class initialization

...

. \[[Bloch 05b|AA. Java References#Bloch 05b]\] 

...



h2. Noncompliant Code Example (background thread)

...



In this noncompliant code example,

...

Code Block
bgColor#FFcccc
 the {{static}} initializer starts a background thread as part of class initialization. The background thread attempts to initialize a database connection but needs to wait until initialization of all members of the {{ConnectionFactory}} class, including {{dbConnection}}, has finished. 

{code:bgColor=#FFcccc}
public final class ConnectionFactory {
  private static Connection dbConnection;
  // Other fields ...
	  
  static {
    Thread dbInitializerThread = new Thread(new Runnable() {
      public void run() {
        // Initialize the database connection
        try {
          dbConnection = DriverManager.getConnection("connection string");	 
        } catch (SQLException e) {
          dbConnection = null;	
        }
      }
    });

    // Other initialization, for example, start other threads   
	    
    dbInitializerThread.start();
    try {
      dbInitializerThread.join();
    } catch(InterruptedException ie) {
      throw new AssertionError(ie);
    }
  }
	  
  public static Connection getConnection() {
    if(dbConnection == null) {
      throw new IllegalStateException("Error initializing connection");  
    }
    return dbConnection;
  }
	  
  public static void main(String[] args) {
    // ...
    Connection connection = getConnection();
  }
}
{code}

...

Statically-initialized fields are guaranteed to be fully constructed before they are made visible to other threads (see [CON26-J. Do not publish partially initialized objects] for more information). Consequently, the background thread must wait for the main (or foreground) thread to finish initialization before it can proceed. However, the {{ConnectionFactory}} 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]\] 

...



Similarly, it is inappropriate to start threads from constructors (see [CON14-J. Do not let the "this" reference escape during object construction] for more information). Creating timers that perform recurring tasks and starting them from within code responsible for initialization also creates liveness issues.

...

Compliant Solution (static initializer, no background threads)

This compliant solution uses a static initializer for initialization and does not spawn any background threads from it. All fields are initialized in the main thread.

Code Block
bgColor#ccccff



h2. Compliant Solution ({{static}} initializer, no background threads)

This compliant solution does not spawn any background threads from the {{static}} initializer. All fields are initialized in the main thread.

{code:bgColor=#ccccff}
public final class ConnectionFactory {
  private static Connection dbConnection;
  // Other fields ...

  static {
    // Initialize a database connection
    try {
      dbConnection = DriverManager.getConnection("connection string");
    } catch (SQLException e) {
      dbConnection = null;	
    }        
    // Other initialization (do not start any threads)
  }

  // ...
}

Compliant Solution (ThreadLocal)

This compliant solution uses a ThreadLocal object to initialize the database connection so that every thread can obtain its own instance of the connection.

Code Block
bgColor#ccccff
{code}


h2. Compliant Solution ({{ThreadLocal}})

This compliant solution initializes the database connection from a {{ThreadLocal}} object so that every thread can obtain its own instance of the connection.

{code:bgColor=#ccccff}
public final class ConnectionFactory {
  private static final ThreadLocal<Connection> connectionHolder
    = new ThreadLocal<Connection>() {
      public Connection initialValue() {
        try {
          Connection dbConnection = DriverManager.getConnection("connection string");
          return dbConnection;
        } catch (SQLException e) {
          return null;
        }
      }
    };

  // Other fields ...

  static {
    // Other initialization (do not start any threads)
  }
    
  public static Connection getConnection() {
    Connection connection = connectionHolder.get();
    if(connection == null) {
      throw new IllegalStateException("Error initializing connection");  
    }
    return connection;
  }

  public static void main(String[] args) {
    // ...
    Connection connection = getConnection();
  }
}
{code}

The static initializer can

...

 be used to initialize any other shared, class fields. Alternatively, the fields can be initialized from the {{initialValue()}} method.

...

Exceptions

...

 


h2. Exceptions

*CON03:EX1*:

...

 It is permissible to start a background thread during class initialization provided that the background thread does not access any fields. For example, the {{ObjectPreserver}} class (based on \[[Patterns 02|AA. Java References#Patterns 02]\]) that is shown below provides a mechanism for storing object references, which prevents an object from being garbage-collected, even if the object is not dereferenced in the future.

...



{code
:bgColor
=#ccccff
}
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 HashMap 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) { 
      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);
  }
}

...

{code} 

This is a singleton class (see [CON23-J. Address the shortcomings of the Singleton design pattern] for more information on how to defensively code singleton classes). The initialization involves creating a background thread using the current instance of the class. The thread waits indefinitely by invoking {{Object.wait()}}. Consequently, this object exists for the remainder of the JVM's lifetime. Because the object is managed by a daemon thread, the thread does not hinder a normal shutdown of the JVM.

...



While the initialization does involve a background thread, the background thread does not access any fields, and creates no liveness or safety issues. Consequently, this code is a safe and useful exception to this guideline.


h2.

...

 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

The following table summarizes the examples flagged as violations by Findbugs:

Noncompliant Code Example

Flagged

Message

background thread

No

n/a

The following table summarizes the examples flagged as violations by SureLogic Flashlight:

Noncompliant Code Example

Flagged

Message

background thread

No

No obvious issues

The following table summarizes the examples flagged as violations by SureLogic JSure:

Noncompliant Code Example

Flagged

Message

background thread

No

n/a

Suggestion: The annotation @Starts("nothing") should also apply to static and instance initializers.

Related Vulnerabilities

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

References

...

 

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON03- J | low | likely | high | {color:green}{*}P3{*}{color} | {color:green}{*}L3{*}{color} |



h3. Automated Detection


The following table summarizes the examples flagged as violations by FindBugs: 

||Noncompliant Code Example||Flagged||Message||
|background thread|No|n/a|

The following table summarizes the examples flagged as violations by [SureLogic|http://www.surelogic.com/] Flashlight: 

||Noncompliant Code Example||Flagged||Message||
|background thread|No|No obvious issues|

The following table summarizes the examples flagged as violations by [SureLogic|http://www.surelogic.com/] JSure:

||Noncompliant Code Example||Flagged||Message||
|background thread|No|n/a|

{mc} Suggestion: The annotation @Starts("nothing") should also apply to static and instance initializers. {mc}

h3. Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+CON41-J].

h2. References

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

...



----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|CON02-J. Always synchronize on the appropriate

...

 object]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|CON04-J. Synchronize using an internal private final lock object]