...
- If
ThreadDeath
is left uncaught, it allows the execution of afinally
block which performs the usual cleanup operations. Even thenthough clean-up statements may execute in this case, use of theThread.stop()
method is highly inadvisable whenThreadDeath
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 thrownThreadDeath
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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(); } } |
...