Sub topic 7
Getting Results Back with Callable and Future
In the last chapter you handed tasks to an ExecutorService. Those tasks were Runnables, so they did their work and returned nothing. Often you want an answer back, such as a computed number or a downloaded page. Java gives you two tools for this: Callable and Future.
Callable: a task that returns a value
A Callable is an interface for a task that returns a result. It has one method, call(). That method returns a value and is allowed to throw a checked exception. A checked exception is one the compiler makes you handle with try/catch or throws.
Here is how it compares with Runnable:
| Feature | Runnable | Callable |
|---|---|---|
| Method name | `run()` | `call()` |
| Returns a value | No (`void`) | Yes (any type `V`) |
| Can throw checked exceptions | No | Yes |
| Accepted by `submit` | Yes | Yes |
Both interfaces have a single method, so you can write either one as a lambda. Java looks at the lambda body to decide which one you meant. () -> 6 * 7 gives back a value, so Java treats it as a Callable<Integer>. () -> System.out.println("hi") gives back nothing, so Java treats it as a Runnable.
Future: a ticket for a result that isn't ready yet
When you call submit on an ExecutorService, the task does not run right away on your thread. A pool thread runs it later. submit returns at once with a Future.
A Future is an object that stands for a result that may not exist yet. It works like the claim ticket a dry cleaner gives you: you can come back later and swap it for your item.
The main methods are:
get()waits until the task finishes, then returns its result. Waiting like this is called blocking, which means the calling thread stops until the answer is ready.isDone()returnstrueonce the task has finished. It never blocks.cancel(boolean)tries to stop the task.
A worked example
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<Integer> answer = pool.submit(() -> 6 * 7);
pool.submit(() -> System.out.println("Runs on " + Thread.currentThread().getName()));
System.out.println("Result: " + answer.get());
} finally {
pool.shutdown();
}
}
}Here is what happens, step by step:
newFixedThreadPool(2)creates a pool with two worker threads.- The first
submitsends aCallablethat computes6 * 7. You get back aFuture<Integer>calledanswer. - The second
submitsends aRunnablethat prints the name of the thread running it, such aspool-1-thread-2. answer.get()waits for the first task and returns42.- The
finallyblock shuts the pool down so the program can exit.
The output looks like this. The two lines may come out in either order:
Runs on pool-1-thread-2
Result: 42Why main says `throws Exception`
get() can throw two checked exceptions. InterruptedException means your thread was interrupted while it waited. ExecutionException means the task itself threw an error. This example declares throws Exception to keep the code short. A later chapter shows how to handle task failures properly.
Exercise
You run Future<String> f = pool.submit(() -> "done"); and then call f.isDone() right away, before the pool thread has run the task. What does isDone() return, and what would f.get() do at that moment?
Show answer
isDone() returns false because the task has not finished yet, and it returns right away without waiting. f.get() would block the calling thread until the task finishes, then return the string "done".
Exercise
Is the lambda () -> System.out.println("hi") a Callable or a Runnable when passed to submit, and what does the returned Future's get() give back?
Show answer
It is a Runnable, because the lambda gives back no value. The submit call returns a Future<?>, and get() returns null once the task finishes.