TimeoutException
JavaERRORNotableConcurrency
Operation timed out before completing
Quick Answer
Always pass a timeout to Future.get() and handle TimeoutException explicitly — cancel the future if the timeout is exceeded.
What this means
Thrown by java.util.concurrent operations (Future.get, BlockingQueue.poll) when a blocking call exceeds the specified timeout without completing. A checked exception — it must be handled or declared.
Why it happens
- 1Future.get(timeout, unit) called and the task did not complete in time
- 2CompletableFuture.get() with a timeout on a slow asynchronous operation
Fix
Handle TimeoutException with cancellation
Handle TimeoutException with cancellation
Future<String> future = executor.submit(task);
try {
String result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true); // interrupt the running task
throw new ServiceUnavailableException("Task timed out after 5s");
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}Why this works
Cancelling the future after a timeout interrupts the underlying thread, preventing resource leaks from abandoned long-running tasks.
Code examples
CompletableFuture timeout (Java 9+)java
CompletableFuture.supplyAsync(this::slowOperation)
.orTimeout(3, TimeUnit.SECONDS)
.exceptionally(ex -> "fallback");Same error in other languages
Sources
Official documentation ↗
Java SE Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev