Callable and Future
A Runnable has no return value and no way to report a failure. Callable is the same idea with a result: one method, call, which returns a value and may throw. A Future is the handle to that value, and the four things it answers are the subject of this lesson: the value, a timeout, a cancellation and a failure.
Callable and FutureTask
FutureTask is a future that is also a Runnable, so it can be given to a plain thread. The program starts it and asks for the result:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Task {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<Integer> work = () -> {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
};
FutureTask<Integer> task = new FutureTask<>(work);
Thread thread = new Thread(task, "calc");
thread.start();
System.out.println("done before get: " + task.isDone());
System.out.println("result: " + task.get());
System.out.println("done after get: " + task.isDone());
thread.join();
System.out.println("cancelled: " + task.isCancelled());
}
}
javac -Xlint:all Task.java
java Task
done before get: false
result: 5050
done after get: true
cancelled: false
The states of a future
isDone is false before the task has finished, and get is the call that waits for it: the first line printed before the hundred additions were done, the second waited, and the third sees the future finished. A get on a future that is already done returns at once, which is why the second call costs nothing.
A future is not a value: it is a handle to one. The difference matters when the handle is passed around: a method that takes a Future<Integer> may call get and block, or check isDone and do something else, and the caller of the method chooses.
A timeout
get(timeout, unit) waits at most that long and throws TimeoutException after it. The task keeps running: the timeout is a decision of the waiter and not a stop of the work:
import java.util.concurrent.ExecutionException;
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 Timeout {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<String> slow = pool.submit(() -> {
Thread.sleep(300);
return "finished";
});
try {
System.out.println(slow.get(50, TimeUnit.MILLISECONDS));
} catch (TimeoutException e) {
System.out.println("timed out, done: " + slow.isDone());
}
System.out.println("value: " + slow.get());
System.out.println("done: " + slow.isDone());
pool.shutdown();
}
}
javac -Xlint:all Timeout.java
java Timeout
timed out, done: false
value: finished
done: true
The task slept 300 milliseconds and the caller waited 50, so the first read failed and the task was still running. The second read had no limit and got the value, which shows that nothing was lost. A program that gives up after a timeout and wants the work stopped calls cancel, which is the next section.
Cancelling a task
cancel(true) interrupts the task and marks the future cancelled. cancel(false) only marks it, and the task runs to the end without anybody reading the value. The program cancels a task that sleeps for five seconds:
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Cancel {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<String> task = pool.submit(() -> {
Thread.sleep(5000);
return "never";
});
Thread.sleep(50);
boolean cancelled = task.cancel(true);
System.out.println("cancel: " + cancelled);
System.out.println("cancelled: " + task.isCancelled());
try {
task.get();
} catch (CancellationException e) {
System.out.println("get: " + e.getClass().getSimpleName());
}
pool.shutdown();
System.out.println("terminated: " + pool.awaitTermination(1, java.util.concurrent.TimeUnit.SECONDS));
}
}
javac -Xlint:all Cancel.java
java Cancel
cancel: true
cancelled: true
get: CancellationException
terminated: true
The interrupt ends the sleep with an InterruptedException, which the lambda of a Callable may throw, so the task stops before its five seconds are over and the pool terminates within the second. A get on a cancelled future throws CancellationException, which is unchecked, so the catch is optional and the program that forgets it sees the failure.
What a future is
A future is the answer to the two holes of a plain thread: a result and a failure. It also gives the caller a choice that a thread does not: to wait for ever, to wait a while, to check once and move on, or to give up. Those four are the whole API of the interface, and the classes of the next lessons are built on them.
The one thing a future does not do is carry the work: it is a handle, and the task runs in the pool whether or not somebody reads the result. A program that submits a task and never reads the future has a task whose failure nobody sees, which is why the framework of lesson 121 exists for the case where the results are combined.
Exercises
- Change the timeout of Timeout to 500 milliseconds and print the value the first read gets.
- Cancel a task with cancel(false) and print isCancelled and isDone.
- Write a Callable that throws an exception and print the cause of the ExecutionException.
- Submit two tasks to a pool of two and read the faster one with isDone in a loop.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Callableadd toRunnable?Answer
A return value and a checked exception
call returns a value and may declare an exception, which run cannot.
-
What does
get(timeout, unit)do when the time passes?Answer
It throws TimeoutException and the task keeps running
The timeout belongs to the waiter, and stopping the work needs cancel.
-
What does a cancelled future answer to
get?Answer
CancellationException
The cancellation is a state of its own, and the unchecked exception reports it.
-
What does this program print?
import java.util.concurrent.FutureTask; public class Q1 { public static void main(String[] args) throws Exception { FutureTask<String> task = new FutureTask<>(() -> "done"); task.run(); System.out.println(task.get()); System.out.println(task.isDone()); } }Answer
done / true
run on the FutureTask executes the callable, and the future is done afterwards.
-
What is FutureTask?
Answer
A future that is also a Runnable, so a plain thread can run it
It implements both interfaces, which is how a Callable reaches a bare thread.
-
What does
cancel(false)do?Answer
Marks the future cancelled without interrupting the task
The boolean is the may-interrupt flag, and without it the work runs to the end unseen.
-
Why is a future called a handle?
Answer
It refers to a value that is not computed yet
The value arrives later, and the future is what the caller keeps in the meantime.
-
What does this program print?
import java.util.concurrent.FutureTask; public class Q2 { public static void main(String[] args) throws Exception { FutureTask<Integer> task = new FutureTask<>(() -> 21 * 2); task.run(); System.out.println(task.get()); System.out.println(task.isCancelled()); } }Answer
42 / false
The callable computed 42 and nothing cancelled the future.
-
What does a TimeoutException mean for the task?
Answer
Nothing: the task is still running unless it is cancelled
The waiter gave up, and the work continues in the pool.
-
Why does a program keep the Future of every task it submits?
Answer
The value and the failure are only available through it
A future nobody reads leaves a failure nobody sees, which lesson 121 addresses for combinations.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev