What is the Future.cancel() method in Java?

What is Future in Java?

The executor service’s submit() method submits the task to a thread for execution. However, submit() does not know when the task’s outcome will be available. As a result, the method returns Future, a reference that can be used to retrieve the task’s outcome when it becomes available.

In other languages, such as Javascript, the idea of Future is similar to Promise. Future reflects the outcome of a calculation that will be completed at a later date.

Hence, Future is a placeholder used to store the result of an asynchronous computation.

The cancel() method

The cancel() method attempts to cancel the execution of a task. The possible outcomes of calling this method are as follows:

  • If the task has already been finished, has been canceled, or could not be canceled for any other reason, the attempt to cancel will fail.
  • If the cancel() method is invoked and the task is not yet started, then the task will never get executed.
  • If the task has already begun, the mayInterruptIfRunning parameter determines whether the task’s thread should be interrupted during the attempt to terminate it.

Syntax


boolean cancel(boolean mayInterruptIfRunning)

Parameters

  • boolean mayInterruptIfRunning: The flag to indicate whether to interrupt the thread executing the task.

Return value

This method returns true if the task is successfully canceled. Otherwise, it returns false.

Code

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> stringCallable = () -> {
Thread.sleep(1000);
return "hello edpresso";
};
Future<String> stringFuture = executorService.submit(stringCallable);
int count = 0;
while(!stringFuture.isDone()) {
Thread.sleep(200);
count++;
if(count > 4) stringFuture.cancel(true);
}
String result = stringFuture.get();
System.out.println("Retrieved result from the task - " + result);
executorService.shutdown();
}
}

Explanation

  • Line 1: We import the relevant packages.
  • Line 6: We define a single-threaded executor service.
  • Lines 8-11: We define a callable that sleeps for 1000ms and returns a string.
  • Line 13: We use the submit() method to submit the callable to the executor service. We get a Future as a result of this operation.
  • Line 14: We initialize a counter to zero.
  • Lines 15-19: We sleep for 200ms and check if the counter is greater than 4 until the Future finishes. The moment the counter is greater than 4, we invoke the cancel() method on the Future and pass true for the mayInterruptIfRunning parameter.
  • Line 21: We use the get() method to retrieve the result of the Future.
  • Line 22: We print the result from the Future on the console.
  • Line 23: The executor service is shut down.

Free Resources