Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a java thread?

I google the solution for killing a java thread. And there exists two solutions:

  1. set a flag
  2. using Thread.interrupt

But both of them are not suitable for me. In my thread, I call a third-party api which takes a long time to complete. and I want to let the user to cancel this thread if it takes too much time.

So how can I kill this thread ? Thanks in advance.

like image 800
zjffdu Avatar asked Dec 21 '22 21:12

zjffdu


2 Answers

Thread.interrupt() is the only safe method which is generally applicable. You can of course use other application-level signals (such as a conditional check on a volatile variable) to self-terminate. Other methods (such as all the deprecated Thread.xx methods) can pollute your application's state in non-deterministic ways, and would require reloading all application state.

like image 130
Yann Ramin Avatar answered Dec 24 '22 09:12

Yann Ramin


In theory, you could call the deprecated Thread.stop() method. But beware that this could result in your application behaving in unexpected and unpredictable ways ... depending on what the third party library is actually doing. Thread.stop() and friends are fundamentally unsafe.

The best solution is to modify the 3rd-party library to respond to Thread.interrupt. If you cannot, then ditch it and find / use a better library.

like image 26
Stephen C Avatar answered Dec 24 '22 09:12

Stephen C