Sub topic 7
Getting Results Back with Callable and Future
In the last chapter you handed work to a thread pool with ExecutorService. Those tasks were Runnable objects. A Runnable does its job but cannot give anything back. Real programs often need an answer from a task, such as a price, a file size, or the result of a calculation.
This chapter shows how to get that answer. You will use two tools from the java.util.concurrent package:
Callableis a task that returns a value when it finishes.Futureis an object that stands for a result that may not exist yet. You hold it now and collect the value later.
Why Runnable Is Not Enough
A Runnable has one method, run, and its return type is void. That means it returns nothing. If you want a result out of a Runnable, you have to store it in a shared variable. Earlier chapters showed that shared variables can cause race conditions. A race condition is a bug where the result depends on which thread happens to run first.
A Callable avoids that problem. Its single method, call, returns a value of a type you choose. The pool keeps that value safe and gives it to you through a Future.
| Feature | `Runnable` | `Callable<V>` |
|---|---|---|
| Method name | `run()` | `call()` |
| Returns a value | No (`void`) | Yes, a value of type `V` |
| Can throw checked exceptions | No | Yes (`throws Exception`) |
| Works with `ExecutorService.submit` | Yes | Yes |
| Works with plain `new Thread(...)` | Yes | No |
A checked exception is an exception that Java forces you to catch or declare, such as InterruptedException or IOException. Inside call you can let them escape. Inside run you must catch them yourself.
Your First Callable and Future
Here is a complete program. It submits one task that returns a number and one task that only prints.
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();
}
}
}A typical run prints:
Runs on pool-1-thread-2
Result: 42The two lines may come out in the other order, because the two tasks run at the same time.
Here is what each step does:
Executors.newFixedThreadPool(2)creates a pool with two worker threads.pool.submit(() -> 6 * 7)hands the pool a lambda that returns a value. Java treats it as aCallable<Integer>.submitreturns right away with aFuture<Integer>.- The second
submitgets a lambda that returns nothing. Java treats it as aRunnable. answer.get()waits until the task is finished and then returns42.- The
finallyblock callsshutdown(), so the pool's threads stop once their work is done and the program can exit.
How the Pieces Fit Together
The main thread does not wait when it calls submit. It gets the Future immediately and can do other work. Waiting only happens when you call get().
Blocking means the thread stops at that line and does nothing until something happens. Here, get() blocks the main thread until the result is ready. If the result is already there, get() returns at once.
The Methods on Future
A Future has a few methods you will use often.
| Method | What it does |
|---|---|
| `get()` | Waits as long as needed, then returns the result |
| `get(timeout, unit)` | Waits at most the given time, then throws `TimeoutException` if there is still no result |
| `isDone()` | Returns `true` if the task has finished, failed, or been cancelled. Never waits |
| `cancel(mayInterrupt)` | Tries to stop the task. With `true`, it interrupts the running thread |
| `isCancelled()` | Returns `true` if the task was cancelled before it finished normally |
Waiting With a Time Limit
A plain get() can wait forever if a task hangs. Passing a timeout lets your program decide what to do when an answer takes too long.
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimeoutDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(1);
try {
Callable<String> slow = () -> {
Thread.sleep(2000);
return "finished";
};
Future<String> future = pool.submit(slow);
System.out.println("Done yet? " + future.isDone());
try {
String value = future.get(500, TimeUnit.MILLISECONDS);
System.out.println(value);
} catch (TimeoutException e) {
System.out.println("Not ready after 500 ms");
}
System.out.println("Waiting fully: " + future.get());
System.out.println("Done yet? " + future.isDone());
} finally {
pool.shutdown();
}
}
}Output:
Done yet? false
Not ready after 500 ms
Waiting fully: finished
Done yet? trueThe Callable here calls Thread.sleep, which can throw the checked InterruptedException. No try/catch is needed inside the lambda, because call() is allowed to throw. A timeout does not stop the task. The task keeps running, and the second get() collects its result.
Cancelling a Task
Sometimes you no longer need a result. You can call cancel(true) to interrupt the thread that runs the task.
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CancelDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<String> future = pool.submit(() -> {
Thread.sleep(10_000);
return "too late";
});
Thread.sleep(200);
boolean stopped = future.cancel(true);
System.out.println("cancel returned " + stopped);
System.out.println("isCancelled: " + future.isCancelled());
System.out.println("isDone: " + future.isDone());
try {
future.get();
} catch (CancellationException e) {
System.out.println("get() threw CancellationException");
}
} finally {
pool.shutdown();
}
}
}Output:
cancel returned true
isCancelled: true
isDone: true
get() threw CancellationExceptionThe sleeping task is interrupted and ends early. After a cancel, isDone() is also true, because "done" covers every way a task can end. Calling get() on a cancelled future throws CancellationException.
Running Tasks in Parallel the Right Way
The main reason to use a pool is to run several tasks at the same time. To get that, you must submit all tasks first and call get() later.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ParallelSquares {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(4);
try {
long start = System.currentTimeMillis();
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
int n = i;
futures.add(pool.submit(() -> {
Thread.sleep(1000);
return n * n;
}));
}
int total = 0;
for (Future<Integer> f : futures) {
total += f.get();
}
long elapsed = System.currentTimeMillis() - start;
System.out.println("Total: " + total);
System.out.println("Took about " + elapsed + " ms");
} finally {
pool.shutdown();
}
}
}Each task sleeps for one second, but the program finishes in about 1000 ms, not 4000 ms. All four tasks were running together while the main thread waited on the first get(). The total is 1 + 4 + 9 + 16 = 30.
The line int n = i; matters. A lambda can only use local variables that never change after they are set. i changes every loop, so each task gets its own copy in n.
What get() Can Throw
get() declares several exceptions. You will meet each of them in later chapters, but it helps to know them now:
| Exception | When it happens |
|---|---|
| `InterruptedException` | The thread calling `get()` was interrupted while waiting |
| `ExecutionException` | The task itself threw an exception. The original error is inside it |
| `CancellationException` | The task was cancelled |
| `TimeoutException` | Only with `get(timeout, unit)`: the time ran out |
The examples above declare throws Exception on main to keep them short. The chapter "What Happens When a Task Throws" covers ExecutionException in detail.
Summary
- Use
Callable<V>when a task must return a value or throw a checked exception. submitreturns aFutureat once. The task runs on a pool thread in the background.get()blocks until the result is ready.get(timeout, unit)puts a limit on the wait.isDone()checks without waiting.cancel(true)tries to stop the task.- To run tasks in parallel, submit them all before you call
get()on any of them.
Exercise
You submit () -> "hello".length() to an ExecutorService. What type does submit return, and what does calling get() on it give you?
Show answer
The lambda returns a value, so Java treats it as a Callable<Integer>. submit returns a Future<Integer>, and get() returns 5.
Exercise
A program loops five times. Each pass submits a task that sleeps 1 second and then immediately calls get() on that task's Future. The pool has 5 threads. About how long does it take, and how would you fix it?
Show answer
About 5 seconds, because each get() blocks before the next task is submitted, so the tasks run one after another. To fix it, first submit all five tasks and store their Futures in a list, then loop over the list and call get(). That takes about 1 second.
Exercise
A task is still running when you call future.cancel(true). What do isCancelled(), isDone(), and get() do afterward?
Show answer
isCancelled() returns true and isDone() also returns true. get() throws a CancellationException instead of returning a value.
Exercise
Why can a Callable lambda call Thread.sleep without a try/catch, while a Runnable lambda cannot?
Show answer
Callable.call() is declared with "throws Exception", so checked exceptions such as InterruptedException may escape from it. Runnable.run() declares no checked exceptions, so the lambda must catch InterruptedException itself.