简体   繁体   中英

What is happening underneath the Future.cancel(true)

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.

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/

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...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM