Wiki Markup |
---|
Starting and using background threads during class initialization can result in class initialization cycles and deadlock. 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|AA. Bibliography#Bloch 05b]\]. Consequently, programs must ensure that class initialization is complete before starting any threads. |
...
In this noncompliant code example, the static initializer starts started a background thread as part of class initialization. The background thread attempts attempted to initialize a database connection but should have waited until all members of the ConnectionFactory
class, including dbConnection
, have been were initialized.
Code Block | ||
---|---|---|
| ||
public final class ConnectionFactory { private static Connection dbConnection; // Other fields ... static { Thread dbInitializerThread = new Thread(new Runnable() { @Override 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(); } } |
...
Similarly, it is inappropriate to start threads from constructors (see rule 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 initialized 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) } // ... } |
...
Code Block | ||
---|---|---|
| ||
public final class ConnectionFactory { private static 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 { // 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(); } } |
The static initializer can be used to initialize any other shared , class fields. Alternatively, the fields can be initialized from the initialValue()
method.
...
Wiki Markup |
---|
<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:macro-id="66bad752fb49d220-0c00c67a-4ec6432e-8b0baba9-b9a0bab72a4923be2b2eed5e"><ac:parameter ac:name="">CON20-EX1</ac:parameter></ac:structured-macro> *TSM02-EX0:* Programs are permitted to start a background thread (or threads) during class initialization, provided the thread cannot access any fields. For example, the {{ObjectPreserver}} class (based on \[[Grand 2002|AA. Bibliography#Grand 02]\]) shownthat belowfollows provides a mechanism for storing object references, which prevents an object from being garbage-collected, even when the object is never again de-referenceddereferenced. |
Code Block | ||
---|---|---|
| ||
public final class ObjectPreserver implements Runnable { private static final 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); } } |
This is a singleton class (see rule 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 JVMJava Virtual Machine's (JVM) lifetime. Because the object is managed by a daemon thread, the thread cannot interfere with normal shutdown of the JVM.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6fe96c6698ea7a3c-ef60c3ba-494a42be-9728b856-267c3e78a22c484340347e44"><ac:plain-text-body><![CDATA[ | [[Bloch 2005b | AA. Bibliography#Bloch 05b]] | 8. ", Lazy Initialization " | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="63bec22212908dfa-468d2825-4aa846a3-adcdbb1d-2e4447af62a0692a63f211b2"><ac:plain-text-body><![CDATA[ | [[Grand 2002 | AA. Bibliography#Grand 02]] | Chapter 5, Creational Patterns, Singleton | ]]></ac:plain-text-body></ac:structured-macro> |
...