Lesson · Executors, Thread Pools & Async Programming
Future & Callable: a value that arrives later
16 min readFuture & Callable
A Callable is work that returns an answer and may declare real failures; submit hands back a Future, the claim ticket for that answer. This lesson covers the blocking pull of get, the timeouts and envelopes around failure, cancellation that is only a request, and the structural limit that sent the platform looking for the next model.
Callable: work that has an answer
Runnable.run returns nothing and declares no checked exceptions. That is perfect for fire-and-forget work and impossible for work whose entire point is an answer: a parse, a query, a fetch. Callable<V> is the same idea with a return type, V call() throws Exception.
The throws clause is not decoration. A lambda that reads a file or calls a repository can now declare what it really throws, and the executor captures it instead of losing it, which is what makes the failure survivable rather than terminal (the routing between the two executor paths is the uncaught-exception-handler lesson's subject; here we open the container).
The two interfaces are not interchangeable. A Callable cannot be handed to a Thread, because Thread only accepts a Runnable, and that mismatch is exactly why FutureTask exists.
Callable<Integer> parse = () -> Integer.parseInt(readConfigValue()); // may throw checked exceptions Runnable announce = () -> System.out.println("config parsed"); // no value, nothing declared Future<Integer> ticket = pool.submit(parse); // submit(Callable) returns Future<Integer> pool.execute(announce); // no ticket: there is nothing to collect
| Runnable | Callable<V> | |
|---|---|---|
| Method | void run() | V call() throws Exception |
| Returns | nothing at all | a value, and null is a value |
| Checked exceptions | none declared, so they must be caught inside | declared, so the executor captures them |
| Reaches the pool through | execute(task), or a Thread directly | submit(task), invokeAll, supplyAsync |
Callable exists because work with an answer can fail in ways Runnable cannot declare.
submit: a claim ticket, not the work
An executor never gives you the worker it used, the moment it starts, or the place in the queue. It gives you a Future<V>: an object that will know the outcome. That indirection is the point, because the pool is free to run the task on any thread, replace that thread, or run the task much later, and the object in your hand still resolves to exactly one outcome.
The object you actually hold after submit is a FutureTask, which implements both Runnable and Future. That double identity is old and still useful: the same object can be submitted to a pool or wrapped in a plain Thread, and the code waiting for the result does not care which one ran it.
A future is also single-use. Once the outcome exists, meaning a value, a stored throwable or a cancellation, get keeps returning that outcome and cancel returns false. Running the same work again means creating a new task.
FutureTask<Integer> task = new FutureTask<>(() -> Integer.parseInt(readConfigValue())); executor.execute(task); // the pool runs it, because a FutureTask is a Runnable Integer value = task.get(); // and the very same object is still the Future to read
- The Future is the only handle on the outcome. The pool keeps the task; you keep the ticket.
- Nothing about submit promises a moment. A queued task may start a millisecond later or a second later, and the Future hides that queue entirely.
- The outcome waits inside the Future until it is collected, which is convenient for reading and the reason an unread failure stays invisible.
A Future is a claim ticket: the work ran somewhere else, and the ticket is where the answer waits.
get(): the blocking pull
get() blocks until an outcome exists and then returns the value. It is a pull model: nothing arrives until a thread asks, and the thread that asks is parked for the whole wait, in WAITING rather than in an idle pool.
In code that must not hang, an unbounded wait is a bug of its own, so there is get(timeout, unit). It throws TimeoutException when the budget expires and leaves the task running, because a timeout is a report about your wait and never a cancellation. Stopping the work is the next section's call to make.
The other outcomes are worth knowing by name: InterruptedException if the waiting thread is interrupted (that flag belongs to the caller, not to the task), ExecutionException when the task failed, wrapping the original throwable, and CancellationException when the outcome is a cancellation.
try { Integer value = ticket.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { ticket.cancel(true); // the wait ended, so now there is a decision to make } catch (ExecutionException e) { throw new IllegalStateException("config is not a number", e.getCause()); // unwrap: the cause is the story } catch (InterruptedException e) { Thread.currentThread().interrupt(); // restore the flag before leaving (thread API lesson) throw new IllegalStateException("interrupted while waiting for config", e); }
- Unwrap the failure before you log it.
e.getCause()carries the original throwable and its real stack trace; the envelope alone reads like a framework error. - The timed overload does not stop the work. After a TimeoutException the task is still in the pool, still holding whatever it holds, and still going to produce its side effects.
- isDone() and isCancelled() are the only questions that never block. Everything else either waits or throws, and there is no notification anywhere in the interface, which is the gap the next lesson fills.
get() is a pull: the answer arrives only where somebody asks, and the asking thread is parked until it does.
Future · one ticket, four outcomes
holds Future<Integer>
no worker yet
submit(task) wraps the Callable in a FutureTask and hands it to the pool. What comes back is a claim ticket: the work will happen on a pool thread, and this object is the only handle on its outcome.
cancel(): one call, two ways to ask
cancel(mayInterruptIfRunning) is the only way to say do not bother. The argument decides what happens to a run already in progress; a task that has not started is simply marked cancelled and never runs its body.
cancel(false) is the polite form: a queued task never starts, and a running task finishes what it is doing while the future moves to cancelled. cancel(true) adds an interrupt: it sets the flag on the running thread, and the task stops only where it checks that flag, exactly as the interrupt lesson describes. A task with no check keeps running to its own finish line.
- The return value answers a question about the outcome, not about the body. true means the future was still cancellable; false means the outcome was already decided (completed, or already cancelled), and the stored value stays readable.
- Cancelling a running task races with its own completion. If the task finishes its body after the cancel lands, the value it produced is discarded: the state was already cancelled, so nothing can be stored.
- A cancelled queued task may still occupy a queue slot until a worker dequeues it, where it is discarded without running. The body, its side effects and its exceptions never happen.
- Cancellation is cooperative even in the true form. Interrupting a task that swallows the interrupt, or blocks in a call that ignores it, gives you a cancelled future and a thread that is still working.
cancel(false) stops what has not started; cancel(true) adds a request the running task may ignore.
The four states and the questions you can ask
A future is a small state machine, and almost every surprise in this API is a question about which state it is in. NEW means the task has not started, RUNNING means it has, DONE means an outcome is stored (a value or a throwable), and CANCELLED means the outcome is a cancellation.
The questions map onto those states cleanly. isDone() is true for DONE and for CANCELLED, because in both cases the outcome will never change again. isCancelled() is true only for the cancelled state. get() parks in NEW and RUNNING, returns or throws in DONE, and throws CancellationException in CANCELLED.
| State | What is stored | get() | isDone() / isCancelled() |
|---|---|---|---|
| NEW | nothing yet, the task is queued | blocks until an outcome exists, or until the timeout expires | false / false |
| RUNNING | nothing yet, the task is executing | the same: it blocks | false / false |
| DONE with a value | the returned value, published so the reader sees the writes that produced it | returns the value, and keeps returning it forever | true / false |
| DONE with a failure | the throwable, kept as the cause of an ExecutionException | throws ExecutionException | true / false |
| CANCELLED | the cancellation itself, not a value | throws CancellationException | true / true |
DONE and CANCELLED are both final, which is why isDone() answers true for a cancellation.
Future · four states behind one ticket
every arrow is one call: submit, cancel, or get in its three outcomesNEW
The task is queued. No worker has touched it, and nothing is stored yet.
RUNNING
call() is executing on a pool thread. This state can last as long as the work does.
DONE
An outcome is stored: either the returned value, or the throwable the task produced.
False leaves a running task alone and stops everything that comes after it; true also sets the interrupt flag on the running thread, which the body has to check to stop early. Both paths land in the same final state, and both are final: no arrow leaves CANCELLED.
NEW / RUNNING
get() parks the caller. get(timeout) gives up with TimeoutException and leaves the task running.
DONE · stored value
get() returns the value, and every later get() returns it again without blocking.
DONE · stored failure
get() throws ExecutionException, and the cause is the throwable the task threw.
CANCELLED
get() throws CancellationException, an unchecked exception, and isCancelled() reports true.
isDone() is true in DONE and in CANCELLED, because in both the outcome cannot change again. cancel() returns false once an outcome is decided, and a stored value stays readable. Nothing here moves a state backwards: a future is single use, and a timeout reports on the wait rather than on the work.
What a blocked get() cannot do
The pull model has one structural limit: a thread parked inside get() cannot react to anything else. Fan out five tasks and then call get() on each in turn, and the waiting thread learns nothing until its own turn comes, so a task that finished early has no way to say so.
The workaround is a second thread that polls isDone(), which is a busy loop dressed up as a callback, and it still cannot combine results or chain a follow-up step without hand-written coordination. That gap, a value you can react to rather than a value you must ask for, is what CompletableFuture was built for, and it is the next lesson.
- Await at the edge. get() belongs where blocking is acceptable: a request thread, a batch runner, the end of main. Putting it inside a task that other tasks depend on converts a thread pool into a queue of waits.
- Never get() the future of your own task. A task waiting for its own result waits for a thread that is already busy executing it, which is a deadlock that arrives promptly on a one-thread pool.
- Collect batches with the executor, not a loop.
invokeAllhands you the list of futures after the work is done, andinvokeAnyanswers with the first success, which is exactly what a sequence of blocking gets is trying to imitate.
get() answers what is the value; it cannot answer tell me when there is one.
Futures you own: read them, bound them, cancel them
A future is a promise with an obligation attached: somebody has to collect it. Three habits keep that obligation from turning into a leak or a mystery.
- Read it, or discard it deliberately. A submitted task whose future is dropped still runs and still stores its failure. If nobody will read it, decide that now and make the task log its own failure instead.
- Bound every wait on a request path. Use get(timeout) anywhere a hang is unacceptable, and treat the timeout as an event with a policy: cancel, retry, or fail the request.
- Cancel what you abandon. Work tied to a request that has been cancelled, a client that disconnected, or a batch that was superseded keeps paying for a result nobody will read.
- Await what you own before shutdown. A graceful shutdown gives the pool a chance to finish queued work; futures left unread at that point become invisible losses, and a cancelled one is a decision you can log.
Every future you keep is a question you promised to ask.
The rules in one place
Four outcomes, one ticket, and a small set of questions that never block.
- Callable returns a value and may declare failures; submit wraps it in a Future, and the object itself is a FutureTask that a plain Thread can also run.
- get blocks, get(timeout) gives up on the wait and not on the task, and the failure arrives wrapped in an ExecutionException whose cause is the original throwable.
- cancel(false) stops what has not started, cancel(true) also asks a running task to stop, and both return false once the outcome is decided.
- isDone and isCancelled are the only non-blocking questions, and the missing notification is exactly why CompletionStage exists.
A Future is a claim ticket for work that happened somewhere else.
The timeout that cancelled nothing
get(timeout) throws TimeoutException and leaves the task running: the worker is still busy, the side effects will still land, and no interrupt was sent. Treat the timeout as a decision point, cancel the future when the result no longer matters, and log e.getCause() from ExecutionException rather than the envelope, or the real stack trace stays hidden behind a wrapper.
Interview angles
Why does Callable exist when Runnable works?+
Runnable cannot return a value or declare checked exceptions. Callable<V> does both, so a task that parses, queries or fetches can declare its real failures and hand back a result, and submit captures both in the Future.
What does get() throw, and what is inside what?+
InterruptedException while waiting, TimeoutException from the timed overload, ExecutionException wrapping the throwable the task threw, and CancellationException when the outcome is a cancellation. The cause of the ExecutionException is the task's own exception, which is the one to log.
CancellationException extends IllegalStateException, so it is unchecked and easy to miss in code that only catches the checked pair. ExecutionException is checked precisely so callers cannot ignore a failure without noticing.
What is the difference between cancel(false) and cancel(true)?+
Both mark the future cancelled if the outcome is undecided. false lets a running task finish, true also sets the interrupt flag on the running thread, which the task has to check to stop. A queued task never runs its body either way.
Common misconception: That cancel(true) stops the task. Interruption is a request: a task with no check, or one blocked in a call that ignores interrupts, keeps working while the future already reports cancelled.
Why is isDone() true after a cancel?+
isDone() means the outcome will never change, and a cancellation is such an outcome. isCancelled() distinguishes the two, and get() on that state throws CancellationException instead of returning.
What can get() not do, and what does CompletableFuture change?+
get() is a blocking pull: the waiting thread cannot react to completion, and a finished task cannot announce anything to the code that cares. CompletableFuture adds the push half, with dependent stages, combination and handling, none of which need a parked thread.
Follow-up: How would you react to the first of several tasks finishing, with only Future in hand?
How do you keep futures from leaking or hiding failures?+
Read each one or make its task log its own failure, bound waits with a timeout on request paths, cancel work you no longer need, and await what you own before shutdown. An unread future is where a failure goes to hide.