BackendBench
Coffee

Home โ€บ Java exceptions โ€บ TimeoutException

Checked exception ยท java.util.concurrent

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.TimeoutException

Extends 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

How to fix it

  1. Cancel the future on timeout with future.cancel(true) so resources are released.
  2. Check pool size and queue length; a full pool shows up as timeouts.
  3. Set the timeout from measured latency, with a margin, and keep client and server timeouts consistent.
  4. Return a fallback or an error response for the caller instead of letting the exception escape.

Broken and fixed

fails
String result = future.get(1, TimeUnit.SECONDS); // task keeps running afterwards
works
try {
    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.

Related exceptions

More tools you might need