Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

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

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
bgColor#FFcccc

public final class LazyConnectionFactory {
  private static intConnection numberdbConnection;
  private// staticOther Connection conn;
	  fields ...

  static {
    Thread tdbInitializerThread = new Thread(new Runnable() {
        @Override public void run() {
          // Initialize, athe database connection
          try {
	            conndbConnection = DriverManager.getConnection("connectionstringconnection string");
	          } catch (SQLException e) {
	            conndbConnection = null;	
	
          }
        }
    });
	    
    // Other initialization, for example, start other threads

    tdbInitializerThread.start();
    try {
      tdbInitializerThread.join();
    } catch (InterruptedException ie) {
      throw new AssertionError(ie);
    }
    // Other initialization
    number = 42;
  }
	  
  public static Connection getConnection() {
    if (conndbConnection == null) {
      throw new IllegalStateException("ConnectionError notinitializing initializedconnection");  
    }
    return conndbConnection;
  }
	  
  public static void main(String[] args) {
    System// ..out.println(number.
    Connection connection = getConnection();
  }
}

The code in the static block is responsible for initialization, and starts a background thread. The background thread attempts to initialize a database connection and also assigns to the field number but needs to wait until initialization of the Lazy class has finished.

Wiki Markup
Recall 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 information). Consequently, the background thread must wait for the foreground thread to finish initialization before it can 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]\] 

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 TSM01Similar to this noncompliant code example, threads should not be started 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 those timers from within code responsible for initialization also introduces liveness issues.

Compliant Solution (

...

Static Initializer, No Background Threads)

This compliant solution also uses a static initializer for initialization and does not spawn a background thread from itinitializes all fields on the main thread rather than spawning background threads from the static initializer.

Code Block
bgColor#ccccff

public final class LazyConnectionFactory {
  private static intConnection numberdbConnection;
  private// staticOther Connection conn;fields ...

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

  // ...
}

Compliant Solution (ThreadLocal)

This compliant solution uses initializes the database connection from a ThreadLocal object to initialize a database connection and sets flag to true depending on whether the initialization succeeds. The number field is initialized independently in a static initializer.so that each thread can obtain its own unique instance of the connection.

Code Block
bgColor#ccccff

public final class LazyConnectionFactory {
  private static booleanfinal flag;
  private static int number;

ThreadLocal<Connection> connectionHolder
  static {
    number = 42;   
  }

  private static final ThreadLocal<Connection> connectionHolder
    = new ThreadLocal<Connection>() {
   @Override   public Connection initialValue() {
        try {
          Connection conndbConnection = DriverManager.getConnection("connectionstring");
          flag = true;
    DriverManager.getConnection("connection string");
       return conndbConnection;
        } catch (SQLException e) {
       return null;
   flag = false  }
   }
 };

  // Other fields ...

  static {
   return null;
       // Other initialization (do not start any threads)
  }

  public static Connection getConnection() }{
    }Connection connection = connectionHolder.get();
    if (connection == null) {
     public staticthrow Connectionnew getConnection() {IllegalStateException("Error initializing connection");
    }
    return connectionHolder.get()connection;
  }

  public static void main(String[] args) {
    Connection conn = getConnection();
    System.out.println(flag// ...
    Connection connection = getConnection();
  }
}

It is safe to set shared class variables The static initializer can be used to initialize any shared class field. Alternatively, the fields can be initialized from the initialValue() method. Consequently, each thread will see a consistent value of the flag field.

Exceptions

Anchor
CON20-EX1
CON20-EX1

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 dereferenced Wiki Markup*CON03:EX1*: The {{ObjectPreserver}} class (based on \[[Patterns 02|AA. Java References#Patterns 02]\]) is shown below: This class provides a mechanism for storing object references, which prevents an object from being garbage-collected, even if the remaining program no longer maintains a reference to the object.

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(); // keepKeep this object alive
  }
 
  // Neither this class, nor HashSetHashMap 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) { 
      // Forward to handler
      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 CON23MSC07-J. Address the shortcomings of the Singleton design pattern for how to properly handle Prevent multiple instantiations of singleton objects for more information on how to defensively code singleton classes). The initialization creates involves creating a background thread referencing the object, and the thread itself waits forever. Consequently this object exists 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 lifetime; however, as it (JVM) lifetime. Because the object is managed by a daemon thread, the thread (and object) will not hinder a cannot interfere with normal shutdown of the JVM.

While Although the initialization does involve involves a background thread, the background that thread neither accesses no fields and so creates no deadlocknor 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

CON03

TSM02-J

low

Low

likely

Probable

high

High

P3

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"
\[[Patterns 02|AA. Java References#Patterns 02]\] Chapter 5, Creational Patterns, Singleton

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.TSM02.CSTARTDo not call the "start" method of threads from inside a constructor
SonarQube
Include Page
SonarQube_V
SonarQube_V
S2693Threads should not be started in constructors

Bibliography

[Bloch 2005b]

Chapter 8, "Lazy Initialization"

[Grand 2002]

Chapter 5, "Creational Patterns, Singleton"

Issue Tracking

Tasklist
Review List
Review List
||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?|


...

Image Added Image Added Image AddedCON02-J. Always synchronize on the appropriate object      11. Concurrency (CON)      CON04-J. Synchronize using an internal private final lock object