Java 9 CompletableFuture API improvements – orTimeout
One of the improvements in Java 9 CompletableFuture is the orTimeout
method:
CompletableFuture orTimeout(long timeout, TimeUnit unit)
If not completed before specified timeout, completes CompletableFuture exceptionally with TimeoutException.
Let’s say in the following example, we need the task to be completed in 3 seconds, but the task lasts 6 seconds:
public static void main(String[] args) throws ExecutionException, InterruptedException {
int timeout = 3;
runTask()
.orTimeout(timeout, TimeUnit.SECONDS)
.whenComplete((result, exception) -> {
if (exception == null) {
System.out.println("result: " + result);
} else {
System.out.println("Task is not finished in " + timeout
+ " seconds... Completing with TimeoutException");
}
});
}
[addToAppearHere]
private static CompletableFuture runTask() {
return CompletableFuture.supplyAsync(() -> {
for (int i = 1; i < 6; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("running task - " + i + " seconds");
}
return "completed";
});
}
//output
running task - 1 seconds
running task - 2 seconds
Task is not finished in 3 seconds... Completing with TimeoutException
Exception in thread "main" java.util.concurrent.ExecutionException: java.util.concurrent.TimeoutException