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;
public T get()
This method takes no parameters.
This method returns the result of the computation.
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);}}
process
, which prints the thread that executes the function, sleeps for one second, and returns a string.createFuture
, which uses the supplyAsync()
method to run the process()
method in the common pool of ForkJoinPool
. This function returns a CompletableFuture
.sleep()
, which makes the current thread sleep for the given number of milliseconds.createFuture
method to get the CompletableFuture
.process
supplier function, using the get()
method .get()
method.