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 theFutureobject 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
CompletableFutureand name itresultOfTheFuture. - Line 8: We get a
CompletableFuturethat is in a completed stage using thecompletedFuture()method, passingresultOfTheFutureas 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.