Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The proper way to stop

One change that was introduced in Java 2 to reduce the possibility of deadlock is the deprecation of the Thread class's stop( ), suspend( ), and resume( ) methods.

The reason that the stop( ) method is deprecated is because it doesn't release the locks that the thread has acquired, and if the objects are in an inconsistent state ("damaged"), other threads can view and modify them in that state. The resulting problems can be subtle and difficult to detect. Instead of using stop( ), you should use a flag to tell the thread when to terminate itself by exiting its run( ) method. Here's a simple example:

//: c13:Stopping.java
// The safe way to stop a thread.
import java.util.*;

class CanStop extends Thread {
  // Must be volatile:
  private volatile boolean stop = false;
  private int counter = 0;
  public void run() {
    while(!stop && counter < 10000) {
      System.out.println("Detected stop");
  public void requestStop() { stop = true; }

public class Stopping {
  public static void main(String[] args) {
    final CanStop stoppable = new CanStop();
    new Timer(true).schedule(new TimerTask() {
      public void run() {
        System.out.println("Requesting stop");
    }, 500); // run() after 500 milliseconds
} ///:~

The flag stop must be volatile so that the run( ) method is sure to see it (otherwise the value may be cached locally). The "job" of this thread is to print out 10,000 numbers, so it is finished whenever counter >= 10000 or someone requests a stop. Note that requestStop( ) is not synchronized because stop is both boolean (changing it to true is an atomic operation) and volatile.

In main( ), a CanStop object is started, then a Timer is set up to call requestStop( ) after one half second. The constructor for Timer is passed the argument true to make it a daemon thread so that it doesn't prevent the program from terminating.

  • + Share This
  • 🔖 Save To Your Account