get()
is an instance method of the CompletableFuture
which waits for the processing of the task associated with the CompletableFuture
to finish and retrieve the result. This method optionally takes a timeout period during which it waits for the result. The method throws an exception if the wait is timed out.
Note: Refer to How to retrieve the result of a CompletableFuture in Java? to wait for the result indefinitely.
V get(long timeout, TimeUnit unit)
long timeout
: The maximum amount of time to wait.TimeUnit unit
: The unit of time.This method returns the result of the computation.
import java.util.concurrent.*;public class Main {private static String process(){sleep(2000);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, TimeoutException {CompletableFuture<String> stringCompletableFuture = createFuture();long timeOutValue = 1;TimeUnit timeUnitForTimeOut = TimeUnit.SECONDS;String value = stringCompletableFuture.get(timeOutValue, timeUnitForTimeOut);sleep(2000);System.out.println("Completed Processing. Returned value - " + value);}}
process
that prints the thread executing the function, sleeps for one second, and returns a string.createFuture
. This function uses the supplyAsync()
method to run the process()
method in the common pool of ForkJoinPool
. The function returns a CompletableFuture
.sleep()
that makes the current thread sleep for the given amount of milliseconds.CompletableFuture
by invoking the createFuture
method.timeOutValue
.timeUnitForTimeOut
.process
using the get
method. We pass the timeOutValue
and timeUnitForTimeOut
as arguments to the get()
method.get()
method.When the code above is run, the code throws a TimeoutException
that indicates the task took more time to complete than the wait time period.