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]\] Wiki Markup
Noncompliant Code Example
For example, the main thread responsible for performing class initialization can 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 2005b]. Consequently, programs must ensure that class initialization is complete before starting any threads.
Noncompliant Code Example (Background Thread)
In this noncompliant code example, the static initializer starts a background thread as part of class initialization. The background thread attempts to initialize a database connection but should wait until all members of the ConnectionFactory
class, including dbConnection
, are initializedThis noncompliant code example begins initializing the class Lazy
.
Code Block | ||
---|---|---|
| ||
public final class LazyConnectionFactory { private static volatile boolean initialized = false; Connection dbConnection; // Other fields ... static { Thread tdbInitializerThread = new Thread(new Runnable() { @Override public void run() { // Initialize, for example, a database connection the database connection try { dbConnection = DriverManager.getConnection("connection string"); } catch initialized(SQLException e) { dbConnection = true; null; } } }); // Other initialization, for example, start other threads tdbInitializerThread.start(); try { tdbInitializerThread.join(); } catch (InterruptedException ie) { throw new AssertionError(ie); } // Other initialization} public static Connection getConnection() { if (dbConnection == null) { throw new IllegalStateException("Error initializing connection"); } return dbConnection; } public static void main(String[] args) { System// ..out.println(initialized. Connection connection = getConnection(); } } |
Wiki Markup |
---|
The code in the {{static}} block is responsible for initialization, and starts a background thread. The background thread 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]\] |
Compliant Solution (static
initializer)
Statically initialized fields are guaranteed to be fully constructed before they are made visible to other threads (see TSM03-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 2005b].
Similarly, it is inappropriate to start threads from constructors (see TSM01-J. Do not let the this reference escape during object construction for more information). Creating timers that perform recurring tasks and starting those timers from within code responsible for initialization also introduces liveness issues.
Compliant Solution (Static Initializer, No Background Threads)
This compliant solution initializes all fields on the main thread rather than spawning background threads from the static initializer.
Code Block | ||
---|---|---|
| ||
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 initializes the database connection from a ThreadLocal
object so that each thread can obtain its own unique instance of the connectionThis compliant solution does not spawn a background thread during class initialization and uses a static
initializer.
Code Block | ||
---|---|---|
| ||
public final class LazyConnectionFactory { private static boolean initialized = false; final ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() { @Override public Connection initialValue() { try { Connection dbConnection = DriverManager.getConnection("connection string"); return dbConnection; } catch (SQLException e) { return null; } } }; // Other fields ... static { // Initialize, for example, a database connection initialized = true; } 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) { // System..out.println(initialized. Connection connection = getConnection(); } } |
Compliant Solution (ThreadLocal
)
The static initializer can be used to initialize any shared class field. Alternatively, the fields can be initialized from the initialValue()
method.
Exceptions
Anchor | ||||
---|---|---|---|---|
|
TSM02-J-EX0: Programs are permitted to start a background thread (or threads) during class initialization, provided the thread cannot access any fields. For example, the following
ObjectPreserver
class (based on [Grand 2002]) provides a mechanism for storing object references, which prevents an object from being garbage-collected even when the object is never again dereferencedThis compliant solution uses a ThreadLocal
object to initialize a database connection and sets the initialized
flag to true
depending on whether the initialization succeeds.Code Block | ||
---|---|---|
| ||
public final class ObjectPreserver Lazyimplements Runnable { private static volatilefinal booleanObjectPreserver initializedlifeLine = new falseObjectPreserver(); private static final ThreadLocal<Connection> connectionHolder ObjectPreserver() { Thread thread = new ThreadLocal<Connection>Thread(this) {; thread.setDaemon(true); thread.start(); // Keep this publicobject Connectionalive initialValue() {} // Neither this class nor HashMap will be garbage-collected. // References from HashMap to tryother {objects // will also exhibit this property private static Connection conn = DriverManager.getConnection("connectionstring"final ConcurrentHashMap<Integer,Object> protectedMap = new ConcurrentHashMap<Integer,Object>(); public synchronized void run() { try { initialized = true; wait(); return conn; } catch (SQLExceptionInterruptedException e) { return null; 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 ConnectionObject getConnectiongetObject() { return connectionHolderprotectedMap.get(0); } // Unprotect publicthe staticobjects void main(String[] args) { Connection conn = getConnection();so that they can be garbage-collected public static void unpreserveObject() { SystemprotectedMap.out.printlnremove(initialized0); } } |
This is a singleton class (see MSC07-J. Prevent multiple instantiations of singleton objects 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 persists for the remainder of the Java Virtual Machine's (JVM) lifetime. Because the object is managed by a daemon thread, the thread cannot interfere with normal shutdown of the JVM.
Although the initialization involves a background thread, that thread neither accesses fields nor creates any liveness or safety issues. 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 |
---|
TSM02-J |
Low |
Probable |
High |
P2 | 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" |
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.TSM02.CSTART | Do not call the "start" method of threads from inside a constructor | ||||||
SonarQube |
| S2693 | Threads should not be started in constructors |
Bibliography
Chapter 8, "Lazy Initialization" | |
Chapter 5, "Creational Patterns, Singleton" |
Issue Tracking
Tasklist | ||||
---|---|---|---|---|
| ||||
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name||
|T|M|F|1269649993019|1269700561582|rcs_mgr|"Starting and using background threads during class initialization can result in class initialization cycles and deadlock. *For instance,* 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." ... see suggested words in bold...I am also generally unsure about the use of "can" vs. "may" because deadlocks are a "possibility" so perhaps "may" should be used?|
|
...
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