Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Thinking in Java
Prev Contents / Index Next

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(counter++);
    }
    if(stop)
      System.out.println("Detected stop");
  }
  public void requestStop() { stop = true; }
}

public class Stopping {
  public static void main(String[] args) {
    final CanStop stoppable = new CanStop();
    stoppable.start();
    new Timer(true).schedule(new TimerTask() {
      public void run() {
        System.out.println("Requesting stop");
        stoppable.requestStop();
      }
    }, 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.
Thinking in Java
Prev Contents / Index Next


 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire