Versions Compared

Key

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

Threads and tasks that block on operations involving network or file I/O must provide callers with an explicit termination mechanism to prevent denial-of-service (DoS) vulnerabilities.

Noncompliant Code Example (Blocking I/O, Volatile Flag)

This noncompliant code example uses a volatile done flag to indicate that it whether is safe to shut down the thread, as suggested in rule THI05-J. Do not use Thread.stop() to terminate threads. However, when the thread is blocked on network I/O as a consequence of invoking the readLine() method, it cannot respond to the newly - set flag until the network I/O is complete. Consequently, thread termination may be indefinitely delayed.

Code Block
bgColor#FFcccc
// Thread-safe class 
public final class SocketReader implements Runnable { 
  private final Socket socket;
  private final BufferedReader in;
  private volatile boolean done = false;
  private final Object lock = new Object();

  public SocketReader(String host, int port) throws IOException {
    this.socket = new Socket(host, port);
    this.in = new BufferedReader(
        new InputStreamReader(this.socket.getInputStream())
    );
  }

  // Only one thread can use the socket at a particular time
  @Override public void run() {
    try {
      synchronized (lock) {
        readData();
      }
    } catch (IOException ie) {
      // Forward to handler
    }
  }

  public void readData() throws IOException {
    String string;
    while (!done && (string = in.readLine()) != null) {
      // Blocks until end of stream (null)
    }
  }

  public void shutdown() {
    done = true;
  }

  public static void main(String[] args) 
                          throws IOException, InterruptedException {
    SocketReader reader = new SocketReader("somehost", 25);
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000);
    reader.shutdown(); // ShutdownShut down the thread
  }
}

Noncompliant Code Example (Blocking I/O, Interruptible)

...

Code Block
bgColor#FFcccc
// Thread-safe class 
public final class SocketReader implements Runnable { 
  // otherOther methods...

  public void readData() throws IOException {
    String string;
    while (!Thread.interrupted() && (string = in.readLine()) != null) {
      // Blocks until end of stream (null)
    }
  }

  public static void main(String[] args) 
                          throws IOException, InterruptedException {
    SocketReader reader = new SocketReader("somehost", 25);
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000);
    thread.interrupt(); // Interrupt the thread
  }
}

...

Code Block
bgColor#ccccff
public final class SocketReader implements Runnable {
  // otherOther methods...

  public void readData() throws IOException {
    String string;
    try {
      while ((string = in.readLine()) != null) {
        // Blocks until end of stream (null)
      }
    } finally {
      shutdown();
    }
  }

  public void shutdown() throws IOException {
    socket.close();
  }

  public static void main(String[] args) 
                          throws IOException, InterruptedException {
    SocketReader reader = new SocketReader("somehost", 25);
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000);
    reader.shutdown();
  }
}

...

When additional operations must be performed after emerging from the blocked state, use a boolean flag to indicate pending termination. When supplementing the code with such a flag, the shutdown() method should also set the flag to false so that the thread can cleanly exit from the while loop.

Compliant Solution (Interruptible Channel)

...

This technique interrupts the current thread. However, it stops the thread only because the code polls the thread's interrupted status with the Thread.interrupted() method and terminates the thread when it is interrupted. Using a SocketChannel ensures that the condition in the while loop is tested as soon as an interruption is received, even though the read is normally a blocking operation. Similarly, invoking the interrupt() method of a thread blocked on a java.nio.channels.Selector also causes that thread to awaken.

...

This noncompliant code example shows a thread-safe DBConnector class that creates one JDBC connection per thread. Each connection belongs to one thread and is not shared by other threads. This is a common use case because JDBC connections are intended to be single-threaded.

...

According to the Java API, interface Interface Statement documentation [API 20062014]

By default, only one ResultSet object per Statement object can be open at the same time. As a result, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects.

...

Failure to provide facilities for thread termination can cause nonresponsiveness and DoS.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

THI04-J

Low

Probable

Medium

P4

L3

Bibliography

[API 20062014]

Class Thread, method Method stop, interface
Interface ExecutorService
Interface Statement

[Darwin 2004]

Section 24.3, "Stopping a Thread"

[Goetz 2006]

Chapter 7, "Cancellation and Shutdown"

[JavaThreads 2004]

Section 2.4, "Two Approaches to Stopping a Thread"

[JDK7 2008]

Java Thread Primitive Deprecation

[JPL 2006]

Section 14.12.1, "Don't Stop; "
Section 23.3.3, "Shutdown Strategies

[JavaThreads 2004]

2.4, Two Approaches to Stopping a Thread

[Goetz 2006]

Chapter 7, Cancellation and Shutdown"

 

...