Reliably stopping an unresponsive thread

It may not be possible, at least not reliably in every scenario.

IF I understand the mechanism correctly (and there is some uncertainty there), if the code executes in such a way that there are no safepoints during the execution (for example in counted loops), it is not possible for the JVM to signal to the thread that it should stop (the thread never polls for an interrupt).

In such a scenario, you need to kill the JVM process, rather than the thread.

Some extra reading:

How to get Java stacks when JVM can't reach a safepoint

Counted loops


In a nutshell, there's no 100% reliable way to stop a Thread the way you'd like it.


Why?

This is an explanation for others who don't know why, anyone who knows the issue can skip this.

The way how threads are intended to be terminated forcefully is with the interruption state of the Thread. A Thread should be terminated with its interrupt() method is called which sets a boolean flag to true.

When the interruption flag is set to true, the Thread should terminate itself with virtually no delay.

Anyway the Thread can choose to simply ignore this and keep on running.

This is when the stop() method can be called that forces the Thread to terminate. The problem is that this method messes up concurrency, can damage objects and the program can be corrupted without a warning for the user. See Why the stop() method is deprecated?


At the end I could think of two possible ways, one is basically your way, the other one is safer but more complicated.

As an example, a hostile third party .jar which contains a Thread that refuses to terminate can cause these problems.


Quick & Dirty

This solution isn't completely safe but based on the usage this may be acceptable unless you really like security.

Try to first to call the interrupt() method on the Thread and give it a bit time to terminate.

If the Thread doesn't respond, you can either:

  • terminate the program and warn the user to not run that Thread again.
  • stop() the thread and hope for the best.

Complicated & Safe

The safest solution I can think of is creating a whole new process to run the Thread in. If the Thread doesn't want to terminate after interrupt(), you can just end the process with System.exit(-1) and let the OS handle it.

You need Inter Process Communication to communicate with the other process and that makes it a lot more complicated but also safer.


Related

How do you kill a Thread in Java?

What is an InterruptedException in Java? (Disclaimer: I've answered it)

What does java.lang.Thread.interrupt() do?