Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Eliminated du plicate dbCon NCCE

...

Unfortunately database connections, like sockets, are not inherently interruptible. So this design does not permit a client to cancel a task by closing it if the corresponding thread is blocked on a long running activity such as a join query. Furthermore, it is important to provide a mechanism to close connections to prevent thread starvation caused because of the limited number of database connections available in the pool. Similar task cancellation mechanisms are required when using objects local to a method, such as sockets.

Noncompliant Code Example (database connection)

This noncompliant code example shows a thread-safe class DBConnector that creates a JDBC connection per thread, that is, the connection belonging to one thread is not shared by other threads. This is a common use-case because JDBC connections are not meant to be shared by multiple-threads.

Code Block
bgColor#FFcccc

class DBConnector implements Runnable {
  final String query;
  private final Object lock = new Object();
  private boolean isRunning = false;
  private class MultipleUseException extends RuntimeException {};
  
  DBConnector(String query) {
    this.query = query; 
  }
	
  public void run() {
    synchronized (lock) {
      if (isRunning) {
        throw new MultipleUseException();
      }
      isRunning = true;
    }

    Connection con;
    try {
      // Username and password are hard coded for brevity
      con = DriverManager.getConnection("jdbc:myDriver:name", "username","password");  
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);
    } catch (SQLException e) {
      // Forward to handler
    }
    // ... 
  }  

  public static void main(String[] args) throws InterruptedException {
    DBConnector connector = new DBConnector(/* suitable query */);
    Thread thread = new Thread(connector);
    thread.start();
    Thread.sleep(5000);
    thread.interrupt();
  }
}

Unfortunately database connections, like sockets, are not inherently interruptible. So this design does not permit a client to cancel a task by closing it if the corresponding thread is blocked on a long running activity such as a join query. Furthermore, it is important to provide a mechanism to close connections to prevent thread starvation caused because of the limited number of database connections available in the pool. Similar task cancellation mechanisms are required when using objects local to a method, such as sockets.

Compliant Solution (ThreadLocal)

...