Sub topic 12
Timeouts with orTimeout and completeOnTimeout
This chapter assumes you know how to build a chain with supplyAsync, thenApply and exceptionally. It also assumes you know how join and get wrap exceptions. A future that never completes is one of the most common failures in asynchronous code. A remote call hangs, a lock is never released, or a promise is never completed. Every stage that depends on that future then waits forever.
Java 9 added two methods that put a time limit on a future without blocking a thread:
orTimeout(timeout, unit)completes the future exceptionally with aTimeoutExceptionif it is not done in time.completeOnTimeout(value, timeout, unit)completes the future normally with a default value if it is not done in time.
Both are methods on CompletableFuture. Neither exists in Java 8.
Where timeouts fit
Before Java 9, the only built-in timeout was get(timeout, unit). It blocks the calling thread, which is the opposite of what you want in a pipeline. The table compares the three options.
| Method | Blocks the caller | What happens at the deadline | Future state afterwards |
|---|---|---|---|
| `get(timeout, unit)` | Yes | Throws checked `TimeoutException` to the caller | Unchanged, still incomplete |
| `orTimeout` | No | Future completes exceptionally with `TimeoutException` | Completed exceptionally |
| `completeOnTimeout` | No | Future completes normally with your default | Completed normally |
With orTimeout and completeOnTimeout, the timeout becomes part of the future's own outcome. Every downstream stage sees it through the normal channels: exceptionally, handle or a plain value.
orTimeout: fail when time runs out
The next example starts a task that takes two seconds and gives it 200 milliseconds.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class OrTimeoutDemo {
static String slowCall() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "late";
}
public static void main(String[] args) {
CompletableFuture<String> result = CompletableFuture
.supplyAsync(OrTimeoutDemo::slowCall)
.orTimeout(200, TimeUnit.MILLISECONDS)
.exceptionally(ex -> "fallback after " + ex.getClass().getSimpleName());
System.out.println(result.join());
}
}The program prints fallback after TimeoutException after about 200 ms.
orTimeout returns the same future it was called on. It does not create a new stage. This has two consequences:
- The exception reaches
exceptionallyas a bareTimeoutException, not wrapped in aCompletionException. Wrapping happens when an exception passes from one stage to the next, and here there is no hop. Had you calledthenApplybeforeexceptionally, the handler would receive aCompletionExceptionwhose cause is theTimeoutException. - Anyone else holding a reference to that future sees the timeout too.
If you call join instead of recovering, the usual wrapping applies:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
public class OrTimeoutJoin {
public static void main(String[] args) {
CompletableFuture<String> never = new CompletableFuture<>();
try {
never.orTimeout(100, TimeUnit.MILLISECONDS).join();
} catch (CompletionException e) {
System.out.println("cause: " + e.getCause());
}
}
}This prints cause: java.util.concurrent.TimeoutException. With get() you would instead catch ExecutionException.
completeOnTimeout: degrade instead of fail
Sometimes a late answer is not an error. A recommendations widget can show a generic list, and a price lookup can use a cached value. completeOnTimeout supplies that default directly. No recovery stage is needed.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class CompleteOnTimeoutDemo {
public static void main(String[] args) throws InterruptedException {
AtomicBoolean finished = new AtomicBoolean(false);
CompletableFuture<String> price = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
finished.set(true);
System.out.println("task body finished");
return "live price";
}).completeOnTimeout("cached price", 100, TimeUnit.MILLISECONDS);
System.out.println("value: " + price.join());
Thread.sleep(700);
System.out.println("value after task ended: " + price.join());
System.out.println("task body ran to the end: " + finished.get());
}
}The output is:
value: cached price
task body finished
value after task ended: cached price
task body ran to the end: trueThe future already holds cached price, so the real result arrives too late and is discarded. The task itself was never stopped.
What a timeout does not do
Both methods only complete the future. They do not touch the code that was supposed to complete it.
This matches how cancel(true) behaves on a CompletableFuture. It marks the future as cancelled but does not interrupt the running thread. Neither approach gives you cooperative cancellation of the work. If you need to stop the work, the task must check a flag or deadline itself.
The next diagram shows the race that every timeout sets up.
Mechanics worth knowing
The first completion wins. A future completes once. If the task finishes before the deadline, the timeout does nothing, and the JDK cancels the scheduled timer so it does not linger. If the future was already complete when you call orTimeout, the call is effectively a no-op.
The clock starts when you call the method. The timeout is not measured from when the task began. It is measured from the moment you call orTimeout on that stage. If a stage waits in a queue before it starts, that wait counts against the deadline.
A timeout covers the stage you call it on, including everything upstream. Consider this chain:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class WholeChain {
static String sleepThen(String value, long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return value;
}
public static void main(String[] args) {
CompletableFuture<String> chain = CompletableFuture
.supplyAsync(() -> sleepThen("a", 300))
.thenApply(s -> sleepThen(s + "b", 300))
.orTimeout(500, TimeUnit.MILLISECONDS)
.exceptionally(ex -> "timed out");
System.out.println(chain.join());
}
}The first stage takes 300 ms and the second takes 300 ms more. The 500 ms deadline applies to the whole chain, so this prints timed out. To give each step its own budget, call orTimeout after each step. Each call then starts its own clock when it is called, which is usually earlier than you expect, because the chain is built up front.
Dependent stages may run on the timer thread. The JDK uses one internal daemon thread to fire timeouts. In current OpenJDK implementations, the dependent stages of a future that times out run on that thread, unless you used an Async variant. A slow or blocking callback there would delay every other timeout in the JVM. After a timeout, hand heavy follow-up work to your own executor, for example with thenApplyAsync(fn, executor).
Timing out a shared future safely
Because orTimeout and completeOnTimeout modify the future you call them on, they are risky on a future you share. One consumer's deadline becomes everyone's outcome. The copy() method (Java 9) creates a new future that completes when the original does. Completing the copy does not affect the original, so you can put a deadline on the copy.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class SharedFuture {
public static void main(String[] args) {
CompletableFuture<String> shared = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(600);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "full report";
});
CompletableFuture<String> guarded = shared.copy()
.completeOnTimeout("summary only", 100, TimeUnit.MILLISECONDS);
System.out.println("guarded: " + guarded.join());
System.out.println("shared done yet: " + shared.isDone());
System.out.println("shared: " + shared.join());
}
}The output is guarded: summary only, then shared done yet: false, then shared: full report. One consumer gave up early and the other still received the real result.
Choosing between the two methods
- Use
orTimeoutwhen a late result is a failure that callers must know about. Follow it withexceptionallyorhandleat the boundary where you decide what to do. Log theTimeoutException, retry, or return an error response. - Use
completeOnTimeoutwhen a reasonable substitute exists and a missing result is acceptable. The downside is that the timeout becomes invisible. A default value looks like a normal result, so log or count the substitution if it matters. - Do not use either one as a replacement for a timeout inside the work itself.
Java 8 fallback
If you must support Java 8, you can build the same behavior with a ScheduledExecutorService that calls completeExceptionally on the future after a delay. Create the scheduler once and shut it down when the application stops. A new scheduler per call would leak threads.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Java8Timeout {
private static final ScheduledExecutorService SCHEDULER =
Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "timeout-scheduler");
t.setDaemon(true);
return t;
});
static <T> CompletableFuture<T> withTimeout(CompletableFuture<T> f, long ms) {
SCHEDULER.schedule(
() -> f.completeExceptionally(new TimeoutException("after " + ms + " ms")),
ms, TimeUnit.MILLISECONDS);
return f;
}
public static void main(String[] args) {
CompletableFuture<String> never = new CompletableFuture<>();
String result = withTimeout(never, 100)
.exceptionally(ex -> "recovered from " + ex.getClass().getSimpleName())
.join();
System.out.println(result);
}
}This prints recovered from TimeoutException. It is simpler than the JDK version, which also cancels the timer when the future completes early. This sketch leaves the scheduled task queued until it fires.
Summary
orTimeoutturns a late future into a failed one withTimeoutException.completeOnTimeoutturns it into a successful one with a default.- Both are non-blocking, available from Java 9, and modify and return the future they are called on.
- The deadline covers everything upstream of the stage you call it on, measured from the call.
- Neither method cancels or interrupts the running task.
- Use
copy()before adding a deadline to a future that other code also consumes.
Exercise
A chain is built as supplyAsync(taskA).thenApply(taskB).orTimeout(1, TimeUnit.SECONDS).thenApply(String::length).exceptionally(ex -> -1). The timeout fires. What type of exception does the exceptionally handler receive, and why?
Show answer
It receives a CompletionException whose cause is the TimeoutException. orTimeout completes the stage it was called on with a bare TimeoutException, but the exception then passes into the next stage, the thenApply(String::length) stage. A failure that crosses from one stage into a dependent stage is wrapped in a CompletionException. The handler on that later stage therefore sees the wrapper. Had exceptionally been attached directly to the orTimeout result, it would have received the bare TimeoutException.
Exercise
You write CompletableFuture<Report> f = service.loadReport(); f.completeOnTimeout(EMPTY_REPORT, 2, TimeUnit.SECONDS); and pass f to two components. Component A is happy with the empty report after two seconds. Component B needs the real report no matter how long it takes. What goes wrong, and how do you fix it?
Show answer
completeOnTimeout modifies f itself, so after two seconds both components see EMPTY_REPORT, and B never gets the real report. Give A its own guarded copy: f.copy().completeOnTimeout(EMPTY_REPORT, 2, TimeUnit.SECONDS). The copy completes with the default for A, while f is left untouched and still delivers the real report to B.
Exercise
After a completeOnTimeout fires, the database query inside the original supplyAsync is still running. Name one reason this matters and one way to address it.
Show answer
The query keeps holding a pool thread and a database connection even though nobody will use its result, which can exhaust the pool or the connection limit under load. Address it by setting a timeout on the work itself, such as a JDBC query timeout or an HTTP client request timeout, so the resource is released. The future's timeout and the work's timeout complement each other.