Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: more edits

...

  • If ThreadDeath is left uncaught, it allows the execution of a finally block which performs the usual cleanup operations. Even thenthough clean-up statements may execute in this case, use of the Thread.stop() method is highly inadvisable when ThreadDeath is left uncaught in the target thread, primarily because of two reasons. First, the target thread cannot be forcefully stopped because an arbitrary thread may catch the thrown ThreadDeath exception and simply choose to ignore it. Second, abruptly stopping a thread results in the release of all the locks that it has acquired, violating the guarantees provided by the critical sections. MoreoverFurthermore, the objects end up in an inconsistent state, non-deterministic behavior being a typical outcome.

...

More information about deprecated methods is available in MET15-J. Do not use deprecated or obsolete methods. Also, refer to EXC09-J. Prevent inadvertent calls to System.exit() or forced shutdown for more information on how to prevent preventing data corruption when the JVM is abruptly shut down.

...

This noncompliant code example shows a thread that fills a vector with pseudorandom numbers. The thread is forcefully stopped after a fixed given amount of time.

Code Block
bgColor#FFcccc
public final class Container implements Runnable {
  private final Vector<Integer> vector = new Vector<Integer>(1000);

  public Vector<Integer> getVector() {
    return vector;
  }
  
  public synchronized void run() {
    Random number = new Random(123L);
    int i = vector.capacity();
    while (i > 0) {
      vector.add(number.nextInt(100));
      i--;
    }    
  }

  public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(new Container());
    thread.start();
    Thread.sleep(5000);
    thread.stop();
  }
}

...

This compliant solution stops the thread by using the Thread.interruptedinterrupt() method.

Code Block
bgColor#ccccff
public class Container implements Runnable {
  private final Vector<Integer> vector = new Vector<Integer>(1000);
	  
  public Vector<Integer> getVector() {
    return vector;
  }

  public synchronized void run() {
    Random number = new Random(123L);
    int i = vector.capacity();
    while (!Thread.interrupted() && i > 0) {
      vector.add(number.nextInt(100));
      i--;
    }
  }

  public static void main(String[] args) throws InterruptedException {
    Container c = new Container();
    Thread thread = new Thread(c);
    thread.start();
    Thread.sleep(5000);
    thread.interrupt();
  }
}

...