Course contentsShow
← Java
Lesson 2742 of 2,87050. Executor FrameworkFree lesson

get() with Timeout: Avoiding Indefinite Blocking

Use get(timeout, TimeUnit) to wait for a result with a maximum time limit, throwing TimeoutException if exceeded.

get() with Timeout: Avoiding Indefinite Blocking

You'll learn how to prevent your program from waiting forever when retrieving results from a Future.

The Problem with Blocking Indefinitely

In the previous lesson, you saw Future.get() block until a task completes. But what if the task takes much longer than expected—or never finishes? Your thread could hang indefinitely, freezing your application.

Adding a Safety Net: The Timeout Parameter

Java provides an overloaded version of get() that accepts a timeout:

Future<Integer> future = executorService.submit(() -> {
    Thread.sleep(5000); // Simulates long task
    return 42;
});

try {
    Integer result = future.get(2, TimeUnit.SECONDS);
    System.out.println("Result: " + result);
} catch (TimeoutException e) {
    System.out.println("Task didn't complete within 2 seconds!");
    future.cancel(true); // Optionally cancel the task
} catch (InterruptedException | ExecutionException e) {
    // Handle as before
}

How It Works

Think of it like waiting for a friend at a coffee shop: instead of waiting indefinitely, you check your watch and decide "I'll wait 10 minutes, then leave." The get(timeout, TimeUnit) method does exactly this—it waits up to the specified duration, then throws TimeoutException if the result isn't ready.

When to Use This

  • External service calls: Network requests that might hang
  • User-facing applications: Where responsiveness matters more than completion
  • Resource management: When you need threads back for other work
  • Fail-fast scenarios: Better to timeout and retry than wait forever

Notice that TimeoutException doesn't stop the task automatically—you may want to call cancel() afterward.

Key Takeaway:
Use get(timeout, TimeUnit) to wait for a Future result with a maximum time limit, protecting your application from indefinite blocking by throwing TimeoutException when the deadline is exceeded.