How do you kill a java.lang.Thread
in Java?
One way is by setting a class variable and using it as a sentinel.
Class Outer {
public static volatile flag = true;
Outer() {
new Test().start();
}
class Test extends Thread {
public void run() {
while (Outer.flag) {
//do stuff here
}
}
}
}
Set an external class variable, i.e. flag = true in the above example. Set it to false to 'kill' the thread.
There is a way how you can do it. But if you had to use it, either you are a bad programmer or you are using a code written by bad programmers. So, you should think about stopping being a bad programmer or stopping using this bad code. This solution is only for situations when THERE IS NO OTHER WAY.
Thread f = <A thread to be stopped>
Method m = Thread.class.getDeclaredMethod( "stop0" , new Class[]{Object.class} );
m.setAccessible( true );
m.invoke( f , new ThreadDeath() );
Generally you don't kill, stop, or interrupt a thread (or check wheter it is interrupted()), but let it terminate naturally.
It is simple. You can use any loop together with (volatile) boolean variable inside run() method to control thread's activity. You can also return from active thread to the main thread to stop it.
This way you gracefully kill a thread :) .
I'd vote for Thread.stop()
.
As for instance you have a long lasting operation (like a network request). Supposedly you are waiting for a response, but it can take time and the user navigated to other UI. This waiting thread is now a) useless b) potential problem because when he will get result, it's completely useless and he will trigger callbacks that can lead to number of errors.
All of that and he can do response processing that could be CPU intense. And you, as a developer, cannot even stop it, because you can't throw if (Thread.currentThread().isInterrupted())
lines in all code.
So the inability to forcefully stop a thread it weird.
I want to add several observations, based on the comments that have accumulated.
Thread.stop()
will stop a thread if the security manager allows it.Thread.stop()
is dangerous. Having said that, if you are working in a JEE environment and you have no control over the code being called, it may be necessary; see Why is Thread.stop deprecated?stop()
creates a new ThreadDeathError
error on the calling thread and then throws that error on the target thread. Therefore, the stack trace is generally worthless.stop()
checks with the security manager and then calls stop1()
that calls stop0()
. stop0()
is native code.Thread.stop()
has not been removed (yet), but Thread.stop(Throwable)
was removed in Java 11. (mailing list, JDK-8204243) See this thread by Sun on why they deprecated Thread.stop(). It goes into detail about why this was a bad method and what should be done to safely stop threads in general.
The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.