Sub topic 12
Timeouts with `orTimeout` and `completeOnTimeout`
Assume you know Java lambdas, CompletableFuture, basic threads, and ExecutorService. This chapter uses Java 9 or later because orTimeout and completeOnTimeout were added in Java 9.
An asynchronous operation can take longer than a caller should wait. A timeout gives the operation a deadline. CompletableFuture provides two related methods:
orTimeoutcompletes the future exceptionally with aTimeoutException.completeOnTimeoutcompletes the future normally with a fallback value.
Both methods return the same future, so they can be placed in a fluent chain.
Failing when the deadline expires
Use orTimeout when a late result is an error. The future still runs in the background, but the future returned to your code finishes with a timeout failure if the deadline passes first.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class OrTimeoutDemo {
public static void main(String[] args) {
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("work interrupted", e);
}
return "server response";
});
try {
String result = slow
.orTimeout(100, TimeUnit.MILLISECONDS)
.join();
System.out.println(result);
} catch (java.util.concurrent.CompletionException e) {
if (e.getCause() instanceof TimeoutException) {
System.out.println("request timed out");
} else {
throw e;
}
}
}
}join() throws CompletionException for an unsuccessful future. The actual timeout is the exception's cause. This wrapping is why catching TimeoutException directly around join() does not work.
orTimeout does not interrupt or cancel the supplier automatically. The supplier may continue using a thread and may eventually produce its result. The timed-out future remains failed.
Supplying a fallback value
Use completeOnTimeout when a default value is acceptable. If the original operation finishes before the deadline, its result wins. Otherwise, the future completes with the value you provide.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class CompleteOnTimeoutDemo {
public static void main(String[] args) {
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "fresh data";
});
String value = slow
.completeOnTimeout("cached data", 100, TimeUnit.MILLISECONDS)
.join();
System.out.println(value);
}
}This program prints cached data. The fallback should be clearly distinguishable from a successful live result when that distinction matters. A default value can hide an outage if the program does not record that the timeout occurred.
Choosing the right method
| Requirement | Method | Result after the deadline |
|---|---|---|
| A late operation must be reported as failure | `orTimeout` | Exceptional completion |
| A safe fallback is available | `completeOnTimeout` | Normal completion with the fallback |
The methods are terminal decisions about the future's completion. If both are called on the same future, whichever completion happens first wins. Avoid combining them unless that ordering is deliberate.
Handling timeout results in a chain
You can handle a timeout with the normal error-handling methods. exceptionally converts a failure into a value, while handle receives either the result or the exception.
For example, this chain turns only a timeout into a fallback while preserving other failures:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimeoutRecovery {
public static void main(String[] args) {
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> "response")
.orTimeout(500, TimeUnit.MILLISECONDS)
.exceptionally(error -> {
Throwable cause = error instanceof CompletionException
? error.getCause()
: error;
if (cause instanceof TimeoutException) {
return "timeout fallback";
}
throw new CompletionException(cause);
});
System.out.println(result.join());
}
}In production code, choose the timeout based on the operation and its caller. A user-interface request, an internal service call, and a batch task usually need different deadlines. Apply timeouts at service boundaries, log useful context, and avoid blocking a shared executor while waiting.
Exercise
What is the difference between orTimeout(1, TimeUnit.SECONDS) and completeOnTimeout("default", 1, TimeUnit.SECONDS)?
Show answer
orTimeout causes exceptional completion with a TimeoutException; completeOnTimeout causes normal completion with "default" if the original result is not ready.