0

In question How to timeout a thread the suggested solution works with the ExecutorService class, where one can submit a Runnable object to be executed.

The ExecutorService class provides the two methods shutdown and shutdownNow to stop the execution of all tasks. But the Java API says about shutdownNow:

"Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate."

I was wondering, if there is no way to perform a termination of a task WITH guarantee ?

Community
  • 1
  • 1
John Threepwood
  • 15,593
  • 27
  • 93
  • 149

3 Answers3

1

If the task's implementation is out of your control, then the answer is no.

The implementor of the task is responsible and capable for supplying a way of termination. Without it, even System.exit(-1) may have no effect, if the task opened a daemon thread...

yair
  • 8,945
  • 4
  • 31
  • 50
0

The only way is to use the deprecated Thread.stop(), but it's deprecated for good reasons, and should not be used.

So the answer is no: there is no way to stop a task without this task collaboration. If the task refuses to stop even whan it has been asked to stop, nothing can be done.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

it is possible, however you must respect to lot of things:

1) you have to make sure that InterruptedException is handled correctly, e.g not sinked

2) you have to check thread state, e.g invoke Thread.interrupted

3) restore interrupted state of the thread after test

4) consider consulting this in every custom I/O method or a loop (if appropriate)

I'd suggest to read "Java concurrency in practice", this great book contains the whole chapter dedicated to correct interruption of threads and guarantee that things will work as expected.

jdevelop
  • 12,176
  • 10
  • 56
  • 112