Retrieving Results with Future.get()
What you'll learn: How Future.get() blocks the calling thread until a Callable task completes and returns its computed value.
The Core Mechanism
When you submit a Callable to an ExecutorService, you receive a Future object that represents the eventual result of the computation happening on another thread. To actually retrieve that result, you call Future.get().
Here's the key behavior: get() is a blocking call. When you invoke it, your current thread stops and waits until the background task finishes executing. Only then does get() return the computed value.
How It Works in Practice
ExecutorService executor = Executors.newSingleThreadExecutor();
// Submit a Callable that computes something
Future<Integer> future = executor.submit(() -> {
Thread.sleep(2000); // Simulate long computation
return 42;
});
// This line blocks for ~2 seconds until the task completes
Integer result = future.get(); // result is now 42
System.out.println("Result: " + result);
executor.shutdown();
Your thread reaches future.get() and pauses. Behind the scenes, the executor thread runs the Callable, sleeps for 2 seconds, and returns 42. Only after that computation finishes does get() unblock and hand you the result.
Understanding When Computation Completes
The computation completes when:
- The
Callable'scall()method returns normally (you get the value) - An exception is thrown (you get an
ExecutionExceptionwhen callingget()) - The task is cancelled (you get a
CancellationException)
Until one of these conditions occurs, get() keeps your thread waiting.
Key Takeaway: Future.get() is a blocking operation that retrieves the computed value from a Callable task, halting your thread until the background computation finishes successfully, throws an exception, or is cancelled.