Occasionally we must forcibly stop a thread as a best effort before entirely shutting down the whole JVM. Usually Thread#stop
is cited as a surefire, even if ham-handed and deprecated, way to unconditionally stop a thread. This is not so, however: all the rogue thread has to do to keep itself running is catch ThreadDeath
or a superclass:
public static void main(String[] args) throws InterruptedException {
final Thread t = new Thread() { public void run() {
for (;;)
try { Thread.sleep(Long.MAX_VALUE); }
catch (Throwable t) {
System.out.println(t.getClass().getSimpleName() + ". Still going on...");
}
}};
t.start();
Thread.sleep(200);
t.interrupt();
Thread.sleep(200);
t.interrupt();
Thread.sleep(200);
t.stop();
Thread.sleep(200);
t.stop();
}
This will print
InterruptedException. Still going on...
InterruptedException. Still going on...
ThreadDeath. Still going on...
ThreadDeath. Still going on...
Is there anything else that I could do to really, really stop a thread without killing the whole JVM?