What is CompletableFuture.orTimeout() in Java?
Overview
orTimeout() is an instance method of the CompletableFuture which is used to exceptional timeout if the future is not completed within the given period of time.
Once the waiting period is over, the method throws an exception. This method was introduced in Java version 9.
The orTimeout method is defined in the CompletableFuture class. The class is defined in the java.util.concurrent package. To import the class, check the following import statement:
import java.util.concurrent.CompletableFuture;
Syntax
public CompletableFuture<T> orTimeout(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 same CompletableFuture on which this method is applied.
Code
import java.util.concurrent.*;public class Main {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> completableFuture = CompletableFuture.supplyAsync(() -> {sleep(4000);return "Hello-Educative";});long timeOutValue = 1;TimeUnit timeUnit = TimeUnit.SECONDS;completableFuture.orTimeout(timeOutValue, timeUnit).get();}}
Explanation
- Line 1: We import the relevant packages and classes.
- Line 5: We define a function called
sleep(). - Line 15: We get the
CompletableFutureby invoking thecreateFuturemethod. - Line 16: We call the
sleep()method. - Line 23: We call the
orTimeout()method in themainfunction.
The code above throws a TimeoutException, indicating that the future’s completion took longer than expected.