Ensure that a task is interruptible

 ̄綄美尐妖づ 提交于 2019-12-01 21:38:13

How to ensure that my tasks are responsive to interruption when I call Future.cancel()?

Calling future.cancel(...) will stop the task it has not been run yet. If it is being run then if you use future.cancel(true) it will interrupt the running thread.

To stop the thread you need to test the thread interrupt flag:

if (!Thread.currentThread().isInterrupted()) {
   ...

And you need to handle handle InterruptedException appropriately. For example:

try {
    Thread.sleep(...);
} catch (InterruptedException e) {
    // re-establish the interrupt condition
    Thread.currentThread.interrupt();
    // probably stop the thread
    return;
}

See my answer about threads not interrupting.

In your task Runnable, make sure at different levels where you do a interrupt check. Something like:

while(!Thread.currentThread().isInterrupted()){
    //do something
}

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 running task. This is kind of a way to know when to terminate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!