Timeout-Based Result Retrieval with get(timeout)
You'll learn how to avoid waiting indefinitely for a task result by setting a maximum wait time.
Why Timeouts Matter
When you call Future.get() without arguments, your thread blocks indefinitely until the task completes. But what if a task hangs, encounters an unexpectedly slow operation, or never finishes? Your application could freeze waiting for a result that never arrives.
The overloaded get(long timeout, TimeUnit unit) method solves this problem by letting you specify a maximum waiting period.
How It Works
This method attempts to retrieve the result, but only waits up to the specified duration. If the task completes within that time, you get the result normally. If the timeout expires before completion, the method throws a TimeoutException.
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> slowTask = () -> {
Thread.sleep(5000); // Simulates 5-second operation
return "Completed";
};
Future<String> future = executor.submit(slowTask);
try {
// Wait maximum 2 seconds
String result = future.get(2, TimeUnit.SECONDS);
System.out.println(result);
} catch (TimeoutException e) {
System.out.println("Task took too long!");
future.cancel(true); // Optionally cancel the slow task
} catch (ExecutionException e) {
System.out.println("Task failed: " + e.getCause());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
executor.shutdown();
Handling TimeoutException
When a timeout occurs, you typically have options:
- Cancel the task using
future.cancel(true)to stop wasting resources - Retry with a longer timeout or different strategy
- Fall back to a default value or alternative approach
Key Takeaway: Use Future.get(timeout, TimeUnit) to protect your application from indefinitely blocking on slow or stuck tasks, and always handle TimeoutException to gracefully recover from delays.