Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
iscancelled
completablefuture

What is CompletableFuture.isCancelled() in Java?

abhilash

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");
        }
    }
}
Implementation of the isCancelled() method

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 a Future 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 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.
  • 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 the get() method. We then print it on the console.

RELATED TAGS

java
communitycreator
iscancelled
completablefuture
RELATED COURSES

View all Courses

Keep Exploring