What is CompletableFuture.isCompletedExceptionally() in Java?

isCompletedExceptionally() is an instance method of the CompletableFuture. It checks whether the future is completed with any exceptions. The possible reasons for a future to complete exceptionally are:

  • Any of the stages of the future get cancelled.
  • The completeExceptionally method is invoked explicitly.
  • There is an abrupt termination of any of the stages of the future.

The isCompletedExceptionally 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 isCompletedExceptionally()

Parameters

The method has no parameters.

Return value

This method returns true if the future is completed exceptionally. Otherwise, it returns false.

Code

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> completableFuture = new CompletableFuture<>();
RuntimeException runtimeException = new RuntimeException("Runtime Exception");
boolean flag = completableFuture.completeExceptionally(runtimeException);
if(flag) System.out.println("Future moved to completed stage");
if(completableFuture.isCompletedExceptionally()) System.out.println("Future completed exceptionally");
Integer result = completableFuture.get();
System.out.println("Result - " + result);
}
}

Explanation

  • Line 1: We import the relevant classes.
  • Line 5: We create a completable future that is incomplete using the constructor of the CompletableFuture class.
  • Line 6: We define the exception to be thrown.
  • Line 7: Using the completeExceptionally() method, the future we create in line 5 is moved to the completed stage. This is done with the exception defined in line 6. The completeExceptionally() method returns a Boolean stored in the flag variable.
  • Line 8: Depending on the flag value, we print whether the future was moved to the completed stage or not.
  • Line 9: We check whether the future was completed exceptionally using isCompletedExceptionally().
  • Line 10: We retrieve the value of the future using the get() method. At this point, the exception defined in line 6 is thrown.
  • Line 11: We print the retrieved value.