I google the solution for killing a java thread. And there exists two solutions:
But both of them ar
You can invoke the stop
method on the Thread object but it is strongly recommended that you don't. Read this: http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
Do you have the freedom to make minor changes to the API? Is this blocking call CPU bound or IO bound? If it is IO bound and if you have access to the underlying socket/remote communication object, closing that object can do wonders. It is at least better than stopping the thread.
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.
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.
You can try Thread.stop(), but at your own risk. Optimally, the API you're calling should have a way to interrupt the operation if needed (which is what Thread.interrupt() is for if the API itself does not provide a cleaner way to interrupt its progress, have you tried it?).
Spawn a separate process and kill it using OS facilities. You'll have to call into "C" to do it but it won't be much code. You didn't say what OS you are running on.
In java.util.concurrent.FutureTask, the mechanism of cancellation by timeout is acted as throwing java.util.concurrent.TimeoutException.
You may check out this as if there are something to be interrupted automatically by timeout.