Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Future.cancel() do if not interrupting?

Tags:

From java docs on Future.cancel()

boolean cancel(boolean mayInterruptIfRunning) 

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

My question is what does cancel do if mayInterruptIfRunning is false?
how does it cancel or stop the task from executing if it has already been run?

like image 288
Tom Avatar asked Jan 29 '14 23:01

Tom


People also ask

How does Future cancel work?

Cancelling a Future cancel() method. It attempts to cancel the execution of the task and returns true if it is cancelled successfully, otherwise, it returns false. The cancel() method accepts a boolean argument - mayInterruptIfRunning .

What is thread interrupt?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

What is Future in Java?

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.


1 Answers

If it is not interrupting it will simply tell the future that is is cancelled. You can check that via isCancelled() but nothing happens if you don't check that manually.

Below example code shows how you could do it.

private static FutureTask<String> task = new FutureTask<String>(new Callable<String>() {      @Override     public String call() throws Exception {         while (!task.isCancelled()) {             System.out.println("Running...");             Thread.sleep(1000);         }         return "The End";     }  });  public static void main(String[] args) throws InterruptedException {     new Thread(task).start();     Thread.sleep(1500);     task.cancel(false); } 

The task is started, and after 1.5 iterations told to stop. It will continue sleeping (which it would not if you interrupted it) and then finish.

like image 110
zapl Avatar answered Sep 22 '22 12:09

zapl