Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added normative text; some sentences were activated

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.

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 needs to wait should have waited until all members of the ConnectionFactory class, including dbConnection, have been initialized.

...

Wiki Markup
Statically initialized fields are guaranteed to be fully constructed before they are made visible to other threads. (Seesee rule [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|AA. Bibliography#Bloch 05b]\].

Similarly, it is inappropriate to start threads from constructors . (See 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 does not spawn any initialized all fields on the main thread, rather than spawning background threads from the static initializer. Instead, all fields are initialized in the main thread.

Code Block
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)
  }

  // ...
}

...

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

...

Wiki Markup
<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:macro-id="8cae8452caaa98ae-ee0db826-4a8e49ee-86a3bc5b-2acfaec33babfaf5a021ba8e"><ac:parameter ac:name="">CON20-EX1</ac:parameter></ac:structured-macro>
*TSM02-EX1:* ItPrograms isare permissiblepermitted to start a background thread (or threads) during class initialization, provided the thread doescannot not access any fields. For example, the {{ObjectPreserver}} class (based on \[[Grand 2002|AA. Bibliography#Grand 02]\]) shown below provides a mechanism for storing object references, which prevents an object from being garbage-collected, even ifwhen the object is notnever again de-referenced in the future.

Code Block
bgColor#ccccff
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 see rule MSC16-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 persists for the remainder of the JVM's lifetime. Because the object is managed by a daemon thread, the thread does not hinder a cannot interfere with normal shutdown of the JVM.

While Although the initialization does involve involves a background thread, that thread does not access any fields or create neither accesses fields nor creates any liveness or safety issues. Consequently, this code is a safe and useful exception to this rule.

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="afea6515a5feabb9-fa1fbbd0-4b154c94-82dcbc32-564f6f4b7a8b97641e13be66"><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="d835f9e028a5b763-9112b37e-45694b5f-9c1dbcd4-8dc51baa9e128a85e1f679f1"><ac:plain-text-body><![CDATA[

[[Grand 2002

AA. Bibliography#Grand 02]]

Chapter 5, Creational Patterns, Singleton

]]></ac:plain-text-body></ac:structured-macro>

...