How to ensure that my tasks are responsive to interruption when I call Future.cancel()
?
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> future = executor.submit(task);
try {
future.get(timeout, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true);
}
In your
task
Runnable, make sure at different levels where you do ainterrupt
check. Something like:If your logic in not something like loop, then check for interrupt status right before major computation like database or web-service call.
The idea here is to keep checking interrupt status as when
future.cancel(true)
is called, it ultimately interrupts your thread runningtask
. This is kind of a way to know when to terminate.Calling
future.cancel(...)
will stop the task it has not been run yet. If it is being run then if you usefuture.cancel(true)
it will interrupt the running thread.To stop the thread you need to test the thread interrupt flag:
And you need to handle handle
InterruptedException
appropriately. For example:See my answer about threads not interrupting.