What is CompletableFuture.complete() in Java?

complete() is an instance method of the CompletableFuture class that completes the future with the passed value if the future has not been completed already.

The complete 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

The function has the following syntax:

public boolean complete(T value)

Parameters

The function has only one parameter:

  • T value: The value to set.

Return value

This method returns true if the method call results in the transition of the CompletableFuture to a completed state. 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<>();
Integer valueToSet = 0;
boolean flag = completableFuture.complete(valueToSet);
Integer result = completableFuture.get();
if(flag) System.out.println("Future moved to complete state with value - " + result);
else System.out.println("Future not moved to complete state");
}
}

Explanation

  • Line 1: We import the relevant classes.
  • Line 6: We create a completable future that is incomplete using the constructor of the CompletableFuture class.
  • Line 7: We define the value to be set when the future is complete. This is called valueToSet.
  • Line 8: We use the complete() method to move the future created in line 6 to the completed stage. The value is set to valueToSet. The complete() method returns a boolean stored in the flag variable.
  • Line 9: We retrieve the value of the future using the get() method.
  • Lines 10-11: Depending on the flag value, we print whether or not the future was moved to the completed stage.

Free Resources