Safely Stopping Threads

Stopping threads at arbitrary times can leave objects in inconsistent, half-updated states they could not normally reach.

To avoid this, provide the method that stops the thread at only precise well-defined locations in the thread's execution. If you like you can also add a cleanup() method to be called here as well.

public class StoppableThread extends Thread {
      
  private boolean stopRequested;  
  
  public void run() {
  
    while (true) {
      System.out.println("Hee");
      System.out.println("Ha");
      System.out.println("Ho");
      System.out.println("");
      if (stopRequested) {
        cleanup();
        break;
      }
    }
  
  }  
  
  public void requestStop() {
    stopRequested = true;
  }
  
  private void cleanup() {
    // ...
  }   
  
  }

Previous | Next | Top | Cafe au Lait

Copyright 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 28, 2006