Versions Compared

Key

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

...

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

...

Code Block
bgColor#FFcccc
class StopSocket implements Runnable {
  private final Socket socket;
  
  public void run() { 
    try {
      socket = new Socket("somehost", 25);
      BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String string = null;
      while (!Thread.interrupted() && (string = br.readLine()) != null) { 
        // Blocks until end of stream (null)
      }
    } catch (IOException ie) { 
      // Forward to handler
    }
  }
  
  
  public static void main(String[] args) throws IOException, InterruptedException {
    StopSocket ss = new StopSocket();
    Thread thread = new Thread(ss);
    thread.start();
    Thread.sleep(1000); 
    thread.interrupt();
  }
}

...

This compliant solution closes the socket connection, by having the shutdown() method close the socket. As a result, the thread is bound to stop due to because of a 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 implements Runnable {
  private volatile Socket socket; // Socket needs to be shared 
  
  public void shutdown() throws IOException {
    if (socket != null) {
      socket.close();
    }
  }
  
  public void run() { 
    try {
      socket = new Socket("somehost", 25);
      BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String string = null;
      while ((string = br.readLine()) != null) { 
        // Blocks until end of stream (null)
      }
    } catch (IOException ie) { 
      // Forward to handler
    } finally {
      try {
        shutdown();
      } catch (IOException e) {
        // Handle the exception 
      }
    }
  }


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

...