How to stop a thread correctly if my Thread.interrupt () call fails?

It is well known that no one should stop the execution of processes using Thread.stop ().

Typically, manuals and tutorials suggest using Thread.interrupt () or some boolean variable instead and checking inside the code for that interrupt or variable.

But if I have a library method that takes a very long time to execute, and I want to give the user the opportunity to stop this process? And the library does not give me mechanisms for this (does not check the state of the thread interruption and there are no "stop!" Variables)?

And to add to the bad things, there is either no source code for the library, or it is too large to edit it and add checks to the appropriate places.

Thread.stop () seems to be the only solution here. Or maybe there is a workaround?

+5
source share
5 answers

If this is practical in your situation, create another process and consider it as a unit of work, not a thread. The killing process is much more deterministic, although dedicating the process to what used to be threading may be too difficult for your situation.

+3
source

Why aren't you trying to use sleep (long timeout) when you expect some kind of condition, and if you have not succeeded, you just "come back" from the stream?


Your thread probably works in while (booleanVariable) { },

, volatile, false.

Thread.stop() System.exit(value), , , - /vm, .

+4

, Thread.stop() - , , .

+1

, , , , IO /. (IE , ) Thread.stop() - .

+1

Thread.stop () is deprecated from java 4 onwards. I am reading an article to stop the thread, completing the library call into a separate class that implements the InterruptibleChannel, which is part of java.nio. Interruptibleclasses has a close () method through which another thread can invoke it asynchronously.

0
source

All Articles