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;
public boolean is canceled()
The method has no parameters.
This method returns true
if the future is canceled before its completion. Otherwise, it returns false
.
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");}}}
sleep()
that makes the current thread sleep for the given milliseconds.submit()
method. We get a Future
as a result of this operation.Future
is 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 the cancel()
method on the future. This passes true
for the mayInterruptIfRunning
parameter.isCancelled()
method. If the future is not canceled, we retrieve the future result using the get()
method. We then print it on the console.