We have some code in place already using ThreadPoolExecutor where each thread takes care of tasks like copying files from one machine to another, performing checks and so on. Need a way to stop a thread based on a condition. The internet did yield some posts saying it's doable by using Future. Since the actual code cannot be posted, the below code simulates what we need but it appears that calling Future.cancel(true) doesn't cancel the thread and calling shutdown() doesn't really close down the pool. Please take a look at the below to see if there's anything else needed or a flaw in the code. Appreciate your time!
Parimala Ramdas wrote:it appears that calling Future.cancel(true) doesn't cancel the thread
This call does cancel the submitted task, not the thread.
In your program only task number 4 is cancelled ...take a thorough look at the output, the task no. 4 doesn't appear in the output
- it is canceled so it even does not start:
Parimala Ramdas wrote: and calling shutdown() doesn't really close down the pool.
Thank you Kordal. shutdownNow() worked with the original code.
We changed it a little to simulate the IO operations that our application has to perform and it doesn't stop the loop.
Our requirement is to cancel a task that has already started (like an IO task that checks out files from a repository and copies them to a different machine). If shutdownNow() is unable to stop a loop from executing (as seen below) we are doubtful whether it will stop an IO operation....
You catch an interruption and you throw it away. The only way to safely 'stop' a thread is to interrupt it. So shutdownNow, and other cancel type methods will interrupt the intended threads. You catch that interruption and ignore it, so yeah, your loop keeps going. What you need to do is stop the loop when the thread gets interrupted.
For your IO task - your task has to respond to interruption as well. If it doesn't then you have to detect the interrupt and see if there is something else you can do to make the task end (such as forceably close the Stream, or cause some other exception to occur). But to respond to shutdownNow and cancel you MUST be able to respond to thread interrupt.