What is CompletableFuture.isCancelled() in Java?
isCancelled() is an instance method of the CompletableFuture class. It checks whether the future is canceled before it gets completed normally.
The isCancelled method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class, check the following import statement:
import java.util.concurrent.CompletableFuture;
Syntax
public boolean is canceled()
Parameters
The method has no parameters.
Return value
This method returns true if the future is canceled before its completion. Otherwise, it returns false.
Code
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()that makes the current thread sleep for the given milliseconds. - Line 15: We submit the callable to the executor service using the
submit()method. We get aFutureas 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
Futureis finishing, we sleep for 2 seconds and check if the counter is greater than the wait time counter. The moment it is greater than the wait time counter, we invoke thecancel()method on the future. This passestruefor themayInterruptIfRunningparameter. - Lines 30-35: We check if the future is in a canceled state using the
isCancelled()method. If the future is not canceled, we retrieve the future result using theget()method. We then print it on the console.