How to interrupt the future, but still wait for its completion?
An interesting problem. Your code will not work, because when you cancel Future , as you discovered, you cannot call get() again on it, because it will raise a CancellationException .
If I understand your requirements:
- You should be able to interrupt threads because you want to stop
sleep , wait , etc. - You still want to receive the results of the tasks after they are canceled.
In this case, you should not use Future . Instead, use your own work shells and wait for the ExecutorService finish with executorService.awaitTermination(...) .
If you need the result of your tasks, then your Runnable class will contain the result of the calculation and will have the boolean done flag. The waiting thread will expect that for each Runnable its done flag will be set to true. When the shell completes its run() method, it will set done and notify() to itself. This needs to be done in the finally block.
If the waiting thread is interrupted, it will call executorService.shutdownNow(true) to interrupt all threads, but will continue the loop, waiting for completion.
Something like that.
source share