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?
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With