Home โบ Java exceptions โบ TimeoutException
TimeoutException: causes and fixes
A blocking call with a time limit, such as Future.get(timeout), did not finish in time.
What it looks like
java.util.concurrent.TimeoutExceptionExtends Exception in java.util.concurrent.
What it means
Methods that take a timeout (Future.get(10, SECONDS), CompletableFuture.orTimeout, ExecutorService.invokeAll with a limit, CountDownLatch.await) throw or report TimeoutException when the time elapses. The task itself is not stopped: the future keeps running unless you cancel it, so timing out is a decision about waiting, not about the work.
Common causes
- The task is slower than the limit: a slow database query or remote call.
- Thread pool starvation: the task is queued behind others and has not started.
- A deadlock or a blocked thread that never completes the future.
- A timeout shorter than the realistic latency of the dependency.
How to fix it
- Cancel the future on timeout with
future.cancel(true)so resources are released. - Check pool size and queue length; a full pool shows up as timeouts.
- Set the timeout from measured latency, with a margin, and keep client and server timeouts consistent.
- Return a fallback or an error response for the caller instead of letting the exception escape.
Broken and fixed
String result = future.get(1, TimeUnit.SECONDS); // task keeps running afterwardstry {
return future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
return fallback();
}๐ Unravel the failing code ๐ Unravel the fix
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is TimeoutException a checked or unchecked exception?
TimeoutException is a checked exception (it extends Exception), so the compiler forces you to catch it or declare it with throws.
Which package is TimeoutException in?
It lives in java.util.concurrent, so the import is import java.util.concurrent.TimeoutException;.
What is the first thing to check when I see TimeoutException?
Read the message and the first stack trace line in your own code. The usual causes are: The task is slower than the limit: a slow database query or remote call; and Thread pool starvation: the task is queued behind others and has not started.