Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I immediately terminate a Thread? (Not interrupt)

This is not a question about how to cleanly terminate a thread, ie by calling interrupt on it and having the thread respond appropriately. I cannot modify code the thread is executing in any way.

I specifically want to immediately terminate a Thread, I don't care at all what state things are left in. I know something similar is possible using Thread.stop, however this actually throws a ThreadDeath exception, and for the Thread to terminate this exception cannot be caught. However the code I am dealing with catches this exception and is not rethrowing it.

Thread.destroy() seemed to be what I was looking for, however this method was never implemented. Is there any other way of achieving this?

like image 238
tixopi Avatar asked Nov 15 '15 22:11

tixopi


1 Answers

I believe that there's no way in Java to just kill off a thread like you're describing. As you note in a comment, interrupt won't do what you want. If the thread is executing, it just sets a flag and it's up to the thread to notice it. if the thread is waiting or sleeping, it will throw an InterruptedException.

The only way I can imagine doing what you're describing is to kill the process in which the thread is running. (E.g., call System.exit(int).)

like image 93
Ted Hopp Avatar answered Nov 15 '22 11:11

Ted Hopp