How to get asynchronous task's result with timeout in Java

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.

Syntax


V get(long timeout, TimeUnit unit)

Parameters

  • long timeout: The maximum amount of time to wait.
  • TimeUnit unit: The unit of time.

Return value

This method returns the result of the computation.

Code

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);
}
}

Explanation

  • Line 1: We import the relevant packages and classes.
  • Lines 6-10: We define a function called process that prints the thread executing the function, sleeps for one second, and returns a string.
  • Lines 12-14: We define a function called createFuture. This function uses the supplyAsync() method to run the process() method in the common pool of ForkJoinPool. The function returns a CompletableFuture.
  • Lines 16-22: We define a function called sleep() that makes the current thread sleep for the given amount of milliseconds.
  • Line 25: We get the CompletableFuture by invoking the createFuture method.
  • Line 27: We define the wait time value as timeOutValue.
  • Line 29: We define the wait time unit as timeUnitForTimeOut.
  • Line 31: We try to retrieve the value returned by the supplier function process using the get method. We pass the timeOutValue and timeUnitForTimeOut as arguments to the get() method.
  • Line 33: We invoke the sleep function on the main thread.
  • Line 35: We print the value returned by the 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.