What is happening underneath the Future.cancel(true)

我的梦境 提交于 2019-12-20 02:32:55

问题


Suppose I have a Runnable instance:

class MyTask implements Runnable {

  public void run() {
     //some heavy calculation which takes time
      Thread.sleep(5000)
     //rest code
     ...
  }

}

Then, I use ExecutorService to submit the above task:

ExecutorService service = Executors.newFixedThreadPool(3);
Future<?> task = service.submit(new MyTask());

Now, I can cancel the task by task.cancel(true);. What I have understood is that the task.cancel(true) will interrupt the working thread in which this task is running, like Thread.currentThread().interrupt(). But this only sets a flag to tell that the working thread is interrupted.

My question is: if MyTask Runnable has started running, how actually does future.cancel(true) stops my code in run() continuing executing the rest code? Is there a periodical checking for the working thread's interrupted flag underneath? I mean I don't understand how the code in run() can be canceled by only set the interrupted flag to true.


回答1:


Future.cancel does not guarantee that your worker code will stop executing. What it does is set the interrupted flag and cause any blocking JDK calls to throw an InterruptedException. Your worker code may choose to rethrow the interrupted exception and periodically check the interrupted flag, in which case the cancel mechanism will work. Otherwise you may choose to swallow InterruptedException and disregard the iterrupted flag, in which case the cancel mechanism will do nothing but set the cancelled flag to true.

See http://www.ibm.com/developerworks/library/j-jtp05236/




回答2:


There is a method called isInterrupted(), this tells the running code in the thread that it is interrupted by returning a true/false.

This is usually checked by the methods like wait, sleep which you might invoke in the thread. If however you do not use these methods, then you will have to manually check this method [ isInterrupted() ] to determine whether someone has interrupted your thread.

If by any chance you get a true, you can decide what action to perform (let us say for example: throw a InterruptedException or break from a loop, etc...)



来源:https://stackoverflow.com/questions/26516372/what-is-happening-underneath-the-future-canceltrue

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