Versions Compared

Key

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

Threads always preserve the class invariants when they are allowed to exit normally. Unfortunately, programmers Programmers often try to forcefully terminate threads when they believe that the task is accomplished, the request canceled or the program needs to quickly shutdown.

A few APIs were introduced to facilitate thread suspension, resumption and termination but were later deprecated due to inherent design weaknesses. The Thread.stop() method is one such example. It throws a ThreadDeath exception to stop the thread. Two cases arise:

  • If ThreadDeath is left uncaught, it allows the execution of a finally block which performs the usual cleanup operations. This method is not a good idea because of two reasons. First, no particular thread can be forcefully stopped because an arbitrary thread can catch the thrown exception and simply choose to ignore it. Second, stopping threads leads to the release of all held monitors violating the guarantees provided by the critical sections. Moreover, the damaged objects end up in an inconsistent state with arbitrary behavior being a typical outcome.
  • As a remediation measure, catching ThreadDeath on the other hand can itself ensnarl multithreaded code. For one, this the exception can be thrown anywhere making it difficult to trace it and recover effectively. Also, there is nothing stopping a thread from throwing another ThreadDeath exception while recovery is in progress.

...

This noncompliant code example shows how a thread that forcefully comes to a halt when the Thread.stop() method is invoked. Neither the catch nor the finally block is executed. Needless to say, any monitors that are held monitors are immediately released leaving the object in a delicate state.

Code Block
bgColor#FFcccc
class BadStop implements Runnable {
  public void run() {
    try {
      Thread.currentThread().sleep(1000);
    } catch(InterruptedException ie) { // not executed 
        System.out.println("Performing cleanup"); 
    } finally { // not executed
      finally { System.out.println("Closing resources"); }
    //} not executed
     
    System.out.println("Done!");
  }
}

class Controller {
  public static void main(String[] args) {
    Thread t = new Thread(new BadStop());
    t.start();  
    t.interrupt();  // artificially induce an InterruptedException
    t.stop();  // force thread cancellation
  }
}

...

This compliant example uses a boolean flag called done to indicate whether the thread should be stopped after any necessary cleanup code has finished executing. An accessor method shutdown() is used to set the flag to true upon which the thread will start the cancellation process. The done flag has is also been set immediately after the execution of the finally block statements so that the system does not continue relinquishing resources that it has already released, in the event of done staying false.

Code Block
bgColor#ccccff
class ControlledStop implements Runnable{
  protected volatile boolean done = false;
  public void run() {
    while(!done) {
      try {
        Thread.currentThread().sleep(1000);
      }catch(InterruptedException ie) { System.out.println("Performing cleanup"); }
      finally { 
        System.out.println("Closing resources"); 
        done = true; 
      }
    } 
    System.out.println("Done!");
  }

  protected void shutdown(){
    done = true;
  }
}

class Controller {
  public static void main(String[] args) throws InterruptedException {  
    ControlledStop c = new ControlledStop();
    Thread t = new Thread(c);
    t.start();
    t.interrupt();  // artificially induce an InterruptedException
    Thread.sleep(1000);  // wait for some time to allow the exception
                         // to be caught (demonstration only)
    c.shutdown();
  }
}

...

This noncompliant solution uses the advice suggested in the previous compliant solution. Unfortunately, this does not help in terminating the thread because it is blocked on some network IO due to because of the readLine method. The boolean flag trick does not work in such cases; a good alternative to end the thread is required.

Code Block
bgColor#FFcccc
class StopSocket extends Thread {
  protected Socket s;
  protected volatile boolean done = false;
  public void run() { 
    while(!done) {
      try {
        s = new Socket("somehost",25);
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String s = null;
        while((s = br.readLine()) != null) { 
          // blocks until end of stream (null)
        }
        System.out.println("Blocked, will not get executed until some data is received. " + s);
      } catch (IOException ie) { 
          System.out.println("Performing cleanup"); }
      } finally {
          System.out.println("Closing resources");
          done = true;
      }
    }
  }  

  public void shutdown() throws IOException {
    done = true;
  }
}

class Controller {
  public static void main(String[] args) throws InterruptedException, IOException {
     StopSocket ss = new StopSocket();
     Thread t = new Thread(ss);
     t.start();
     Thread.sleep(1000); 
     ss.shutdown();
  }
}

...

This compliant solution simply closes the socket connection, both using the shutdown() method as well as in the finally block. As a result, the thread is bound to stop due to a socketException SocketException. Note that there is no way to keep the connection alive if the thread is to be cleanly halted immediately.

Code Block
bgColor#ccccff
class StopSocket extends Thread {
  protected Socket s;
  public void run() { 
    try {
      s = new Socket("somehost",25);
      BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String s = null;
        while((s = br.readLine()) != null) { 
          // blocks until end of stream (null)
        }
      System.out.println("Blocked, will not get executed until some data is received. " + s);
    } catch (IOException ie) { 
        System.out.println("Performing cleanup"); }
    } finally {
        System.out.println("Closing resources");
        try {
          if(s != null)
            s.close();
        } catch (IOException e) { e.printStackTrace();/* forward to handler */ }
    }
  }

  public void shutdown() throws IOException {
    if(s != null)
      s.close();
  }
}

class Controller {
  public static void main(String[] args) throws InterruptedException, IOException {
    StopSocket ss = new StopSocket();
    Thread t = new Thread(ss);
    t.start();
    Thread.sleep(1000); 
    ss.shutdown();
  }
}

Risk Assessment

Trying to force thread shutdown can lead to result in inconsistent object state and as a result corrupt the object. Critical resources may also leak if cleanup operations are not carried out as required.

...