Java TimeoutException
A timed Future.get throws TimeoutException when the result is unavailable within the waiting budget. The future can still complete later.
A simple example
TimeoutException
- Start with An unfinished task
- Do this Wait only until a deadline
- Result Time limit reached
Syntax
quote.get(timeout, unit)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaLimit the wait for a shipping quote
A checkout screen has used its entire waiting budget for a carrier quote. The quote is still pending, so the customer should see a pending message while the underlying work remains available.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
class Main {
public static void main(String[] args) throws Exception {
var quote = new CompletableFuture<Integer>();
try {
System.out.println(quote.get(0, TimeUnit.SECONDS));
} catch (TimeoutException pending) {
System.out.println("Quote pending");
}
}
}
Quote pending
A fresh future has no result. The zero wait makes this demonstration immediate and repeatable.
Collect the quote after the wait expires
A customer keeps the checkout open after the shipping estimate times out. The carrier later supplies a price, so checkout can collect it from the original request.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
class Main {
public static void main(String[] args) throws Exception {
var quote = new CompletableFuture<Integer>();
try {
quote.get(0, TimeUnit.SECONDS);
} catch (TimeoutException pending) {
quote.complete(8);
}
System.out.println("Shipping " + quote.get());
}
}
Shipping 8
A timed-out wait leaves the future available for a later result.
Poll a finished download
A document download has already completed when the kiosk checks. Inspect the job using a zero-wait poll. A job that has yet to complete stays in the waiting queue.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
CompletableFuture.completedFuture("download").get(0,TimeUnit.SECONDS);
System.out.println("Result ready");
} catch (TimeoutException problem) {
System.out.println("Still waiting");
}
}
}
Result ready
What to watch for
A timeout ends this wait. Decide separately whether the operation should be cancelled.