Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
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 progressunderway. \[[Bloch 05b|AA. Java References#Bloch 05b]\] 

...

Code Block
bgColor#FFcccc
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.

Wiki Markup
Recall  {{number}} but needs to wait before initialization of the {{Lazy}} class has finished. Remember 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 infoinformation). Consequently, the background thread must wait for the foreground thread to finish initialization before it maycan 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|AA. Java References#Bloch 05b]\] 

...