How to retrieve the result of a CompletableFuture in Java
The get()method is an instance method, which is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. This method indefinitely waits for the processing of the task associated with the CompletableFuture to finish and then retrieves the result.
Note: Refer to "Get the result of an asynchronous task with timeout in Java to learn how to put a timeout on the waiting period in order to retrieve the result of a
CompletableFuture.
We can import the CompletableFuture class by using the following statement:
import java.util.concurrent.CompletableFuture;
Syntax
public T get()
Parameters
This method takes no parameters.
Return value
This method returns the result of the computation.
Code
import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutionException;public class Main {private static String process(){sleep(1000);System.out.println("Current Execution thread where the supplier is executed - " + Thread.currentThread().getName());return "Hello Educative";}private static CompletableFuture<String> createFuture(){return CompletableFuture.supplyAsync(Main::process);}private static void sleep(int millis){try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws ExecutionException, InterruptedException {CompletableFuture<String> stringCompletableFuture = createFuture();String value = stringCompletableFuture.get();sleep(3000);System.out.println("Completed Processing. Returned value - " + value);}}
Code explanation
- Line 1: We import the relevant packages and classes.
- Lines 6–10: We define a function called
process, which prints the thread that executes the function, sleeps for one second, and returns a string. - Lines 12–14: We define a function called
createFuture, which uses thesupplyAsync()method to run theprocess()method in the common pool ofForkJoinPool. This function returns aCompletableFuture. - Lines 16–22: We define a function called
sleep(), which makes the current thread sleep for the given number of milliseconds. - Line 25: We invoke the
createFuturemethod to get theCompletableFuture. - Line 27: We retrieve the value that is returned by the
processsupplier function, using theget()method . - Line 29: We invoke the sleep function on the main thread.
- Line 31: We print the value that is returned by the
get()method.