What is CompletableFuture.cancel() in Java?

Overview

In Java, we use an instance method of the CompletableFuture class, cancel(), that 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, canceled, or could not be canceled for any other reason, then the attempt to cancel will fail.
  • If the cancel() method is invoked and the task has not yet started, the task will not 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.

The cancel() method is defined in the CompletableFuture class, which is defined in the java.util.concurrent package. To import the CompletableFuture class, we use the following import statement.

import java.util.concurrent.CompletableFuture;

Syntax


boolean cancel(boolean mayInterruptIfRunning)

Parameters

boolean mayInterruptIfRunning: This is 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.

Example

import java.util.Random;
import java.util.concurrent.*;
public class Main {
static void sleep(int millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
sleep(4000);
return "Hello-Educative";
});
int count = 0;
int waitTimeCounter = new Random().nextInt(3);
while(!completableFuture.isDone()) {
sleep(2000);
System.out.println("Waiting...");
count++;
if(count > waitTimeCounter) completableFuture.cancel(true);
}
if(!completableFuture.isCancelled()){
String result = completableFuture.get();
System.out.println("Retrieved result from the task - " + result);
}else {
System.out.println("The future was cancelled");
}
}
}

Explanation

  • Lines 1-2: We import the relevant packages.
  • Lines 6-12: We define a function called sleep(). It makes the current thread sleep for the given amount of milliseconds.
  • Line 15: We use the submit() method to submit the callable to the executor service. We get a CompletableFuture class as a result of this operation.
  • Line 20: We initialize a counter to zero.
  • Line 21: We initialize the wait time counter to a random value.
  • Lines 23–28: While the CompletableFuture is finishing, we call sleep() for two seconds and check if the counter is greater than the wait time counter. When it is greater than the wait time counter, we invoke the cancel() method on the Completablefuture. Then, we pass true for the mayInterruptIfRunning parameter.
  • Lines 30-35: We use the isCancelled() method to check if the Completablefuture class is in a canceled state. If the Completablefuture is not canceled, we retrieve the result using the get() method. Finally, we print it on the console.

Free Resources