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;
The function has the following syntax:
public boolean complete(T value)
The function has only one parameter:
T value
: The value to set.This method returns true
if the method call results in the transition of the CompletableFuture
to a completed state. Otherwise, it returns false
.
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");}}
CompletableFuture
class.valueToSet
.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.get()
method.flag
value, we print whether or not the future was moved to the completed stage.