How to unconditionally stop a thread

Sometimes we need to forcefully stop the thread as the best effort before completely shutting down the entire JVM. Typically, Thread#stop quoted as true, even if ham-handed and deprecated, a way to unconditionally stop a thread. However, this is not the case: the entire rogue thread that must be executed in order to continue to work 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(); } 

Will open

 InterruptedException. Still going on... InterruptedException. Still going on... ThreadDeath. Still going on... ThreadDeath. Still going on... 

Is there anything else I could do to really stop the thread without killing the entire JVM?

+8
java
source share
2 answers

Not. There is no built-in easy way to really stop a thread.

Such a method, destroy, was planned, but not implemented :

Outdated. This method was originally developed to destroy this stream without any purification. Any monitors that he held would remain locked. However, this method has never been implemented. If this were implemented, then this would be a dead end form that could be suspended (). If the target thread held a lock protecting a critical system resource when it was destroyed, no thread will ever be able to access that resource again. If another thread has ever tried to lock this resource, this will result in a deadlock. Such deadlocks usually appear as β€œfrozen” processes.

Threads are not intended for this. They do not provide security. Another thread might also end the JVM itself - or create other problem threads.

See Why Thread.stop, Thread.suspend, and Thread.resume are deprecated for more information. You can read why here.

+5
source share

There is no guarantee that this thread can be stopped in Java. The most powerful way is Thread.stop, but this is an accident awaiting what happened. Alternatives are using Thread.interrupt and checking the thread with a flag, but both rely on a correctly encoded thread and, in the case of a flag, regularly check it.

Personally, I would make sure I didn't catch ThreadDeath. Stop is a bad way to stop a thread, but at least you should get a notification until you catch ThreadDeath.

0
source share

All Articles