What is CompletableFuture.completedFuture() in Java?

Overview

completedFuture() is a static method of the CompletableFuture class and is used to get a new CompletableFuture that is in the completed stage, with the passed value as the result of the future.

The completedFuture 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 static <U> CompletableFuture<U> completedFuture(U value)

Parameters

  • U value: The result of the Future object created.

Return value

This method returns a new completable future.

Code

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
String resultOfTheFuture = "hello-educative";
CompletableFuture<String> stringCompletableFuture = CompletableFuture.completedFuture(resultOfTheFuture);
String value = stringCompletableFuture.get();
System.out.println("Returned value - " + value);
}
}

Explanation

  • Line 1: We import the relevant packages and classes.
  • Line 6: We define the result of the completed CompletableFuture and name it resultOfTheFuture.
  • Line 8: We get a CompletableFuture that is in a completed stage using the completedFuture() method, passing resultOfTheFuture as the argument to the method.
  • Line 10: We retrieve the result of the completedFuture() obtained in Line 8.
  • Line 12: We print the result to the console.

Free Resources