A future is an object that stands for a result that is not ready yet. You start slow work (a network call, a query, a computation on another thread), get a future back at once, and carry on; when you need the value you ask the future, which hands it over, waits for it, or reports the error the work ended with. The promise is the other end: the side that does the work completes it, exactly once, with a value or an exception. Java's CompletableFuture, JavaScript's Promise, Python's concurrent.futures and C++'s std::promise/std::future are all this pattern.
Think of it like
The buzzer at a burger counter
You order, pay, and get a buzzer instead of food. The buzzer is the future: you can sit down, talk, check your phone, and the kitchen keeps working on your order. When the burger is ready the kitchen completes the order and the buzzer goes off; if they ran out of buns, it goes off too, and the person at the counter tells you what went wrong instead of letting you wait forever. If you walk up to the counter before it buzzes, you stand there and wait: that is a blocking get(). And you can leave a note ("bring it to table 7"), which is a callback: whoever finishes the order carries it out.
The problem
A product page needs two things from slow services: the price (about 400 ms) and the stock count (about 500 ms, and today the stock service times out). It also has 300 ms of its own work: rendering the header, the images and the description. Done one after the other on one thread, the page takes 400 + 500 + 300 = 1200 ms, which is the One by one version in the visualizer above. The waits are spent doing nothing, so the obvious move is to fetch on other threads while the page renders. A first attempt hands each fetch to a thread and lets the threads put their results into fields:
class ProductPage {
Integer price, stock; // written by the worker threads
void show() {
new Thread(() -> price = fetchPrice()).start();
new Thread(() -> {
try {
stock = fetchStock();
} catch (IOException e) {
log(e); // the caller never hears of it
}
}).start();
renderPage(); // 300 ms of other work
display(price, stock); // hope the fetches are done by now
}
}This is the Plain fields version in the visualizer, and it is fast: the page is "ready" after 300 ms. It is also wrong in three ways.
- Nothing waits for the result. The caller reads the fields when it is done, not when the workers are. With Caller first, C shows the page at step 4 with
price null, stock null, and never reads too early breaks. With Stock is slow, the price has arrived but the stock fetch is still running at step 12. Adding adoneflag and a busy loop (while (!done) {}) burns a CPU while waiting, and withoutvolatileor a lock the Java memory model does not even promise that the loop sees the flag change (see Double-Checked Locking for that kind of bug). - The error disappears. The stock fetch fails, the worker logs the
IOException, and the field staysnull. Even with Caller starts late, where both fetches finish before C reads anything, C showsstock nullas if it were a number, and no exception lost breaks at step 14. Anullcannot say whether the value is missing, late or failed. - Every caller reinvents it. Fields, flags, a lock to make them visible, a way to wake the waiter, a place for the exception, one-time completion: each piece is easy to get wrong and none of it is about product pages.
The pattern
Intent: represent the result of an asynchronous computation as an object. The code that starts the work gets a future right away and can pass it around, wait on it, or attach what to do next; the code that does the work holds the promise and completes it once, with a value or with an error. The two words come from late-1970s research on parallel languages (Friedman and Wise's promise, 1976; Baker and Hewitt's future, 1977), and today they usually name the two sides of one object: Scala's Promise and Future, C++'s std::promise and std::future.
- Future (the read side)
- A handle to a result that may not exist yet. You can ask whether it is done, block until it is (
get()), or register a continuation. In the visualizer,priceandstock, each with a state (PENDING, DONE or FAILED), a value or an error, and a list of callbacks. - Promise (the write side)
- The right to complete the future:
complete(value)orfail(error). Only the producer holds it. Java'sCompletableFutureis both sides in one object; C++ and Scala keep them separate so a consumer cannot complete a result it should only read. - Completion
- The one-time move from PENDING to DONE (with a value) or FAILED (with an exception). It happens at most once: a second
completechanges nothing and returnsfalse. Completing wakes every thread blocked inget()and runs the registered callbacks. - Blocking get
get()returns the value if the future is done, throws if it failed, and otherwise waits. Built from a lock and a condition: lock,while (state == PENDING) done.await(), unlock. In Java the failure arrives wrapped in anExecutionException.- Continuation (callback)
- Code to run with the result once it exists:
thenAccept(cache::put),then(p => ...),add_done_callback(fn). The caller never blocks. If the future is still pending, the completing thread runs it later; if it is already done, it runs at once (in Java and Python, on the thread that registers it). - Combinator
- An operation that builds a new future from others: transform a value (
thenApply,then), chain another asynchronous step (thenCompose), wait for all (allOf,Promise.all) or the first (anyOf,Promise.race), recover from failure (exceptionally,catch).
CompletableFuture<Integer> price = supplyAsync(this::fetchPrice, pool);
CompletableFuture<Integer> stock = supplyAsync(this::fetchStock, pool);
price.thenAccept(cache::put); // continuation: no waiting here
renderPage(); // overlaps both fetches
int p = price.join(); // waits only if not done yet
String s;
try {
s = String.valueOf(stock.get());
} catch (ExecutionException e) { // the worker's IOException, wrapped
s = "unknown";
}
display(p, s);What the visualizer shows
- Versions: Plain fields (the Before above), Futures (a future built by hand from a lock, a condition and four fields, the code in the side panel) and One by one (the timing baseline, one thread doing everything).
- Steps: each step is one atomic action of one thread: a 100 ms slice of a fetch or of rendering, a lock, a check, a wait, a completion, a callback. Locking and signalling are treated as instant.
- Invariants: never reads too early (no result is used before its fetch finished), completes at most once, gets the value written and no exception lost. They are checked after every step.
- Results and the page: the two futures with their state, value or error, waiting callbacks and who is asleep in
get(); how far each fetch is; thecachethe callback writes and the thread that ran it; the page C showed; and when the page would be ready if every thread had its own core. - Threads over time: a lane per thread. Violet is a thread asleep in
get(), sky blue a thread woken and waiting to re-acquire the future's lock. The stats count C's blocked steps and the page-ready time. - Schedules: Caller first (C runs until it has to wait), Stock is slow (the price arrives during rendering, the stock only after C asked for it), Caller starts late (both fetches finish first), Seeded random, and Manual, where you choose which thread runs next.
Walkthrough
- 1
C registers a callback (steps 1 to 3)
With Futures and Caller first, C locks
price.lock, finds the price PENDING and addscache::putto its callbacks. It does not wait: the callback will run whenever the price arrives. - 2
C renders and asks for the price (steps 4 to 9)
C renders the page for 300 ms, then calls
price.get(): lock, check, still PENDING, so it waits onprice.done, which releases the lock. C's lane turns violet. With this schedule C has finished all its own work before either fetch started. - 3
F1 completes the price and wakes C (steps 10 to 16)
F1 spends 400 ms in
fetchPrice(), gets 25, locks, sets DONE and the value, takes the callback list and callssignalAll(). C wakes up but cannot continue until F1 unlocks; its lane turns sky blue. - 4
The callback runs on F1 (step 17)
After unlocking, F1 runs
cache::putwith 25. The callback runs on the thread that completed the future, not on C, which is still waiting to be scheduled. - 5
F2 fails the stock future (steps 18 to 25)
F2 spends 500 ms in
fetchStock(), which throws. F2 catches it and callsstock.fail(e): state FAILED, errorIOException. Nobody is waiting onstock.doneyet, so the broadcast wakes no one, but the error is now stored in the future. - 6
C gets the price (steps 26 to 29)
C re-acquires
price.lock, checks again (thewhileloop), finds DONE, unlocks, andget()returns 25: the value F1 stored, never earlier. - 7
The failure reaches C (steps 30 to 35)
stock.get()finds FAILED and throws anExecutionExceptionwrapping F2'sIOException. C catches it, showsprice 25, stock unknown, and the page is ready after 500 ms: the longest fetch, not the 1200 ms sum. C spent 17 of the 35 steps blocked. - 8
Try the other schedules
With Stock is slow,
price.get()does not wait at all (step 20),stock.get()sleeps at step 25, and F2'sfailwakes it at step 28: a failure wakes a blockedget()just like a value does. With Caller starts late, both futures are complete before C registers the callback, sothenAcceptrunscache::puton C itself (step 19).
Before and after
Before: plain fields
- The caller reads whatever is in the field when it is ready
nullmeans missing, late or failed, and nobody can tell which- The worker's exception is logged and lost
- Waiting means flags, busy loops or sleeps, written again by every caller
- Correct only when the timing happens to work out
With futures
get()returns only after completion, and only blocks if it has to- The future carries the value or the exception, so failure reaches the caller
- Completes once; every waiter wakes, every callback runs once
- The waiting logic lives in one tested class (or the library)
- Fetches overlap: about the longest one, not the sum
| Schedule | Plain fields | Futures | One by one |
|---|---|---|---|
| Caller first | Never reads too early breaks at step 4 (price null, stock null); no exception lost at 14 | All hold; 35 steps, C blocked 17, page ready after 500 ms | All hold; 14 steps, 1200 ms |
| Stock is slow | Never reads too early breaks at step 12 (stock null); no exception lost at 14 | All hold; 35 steps, C blocked 5, page ready after 500 ms | All hold; 1200 ms |
| Caller starts late | No exception lost breaks at step 14 (price 25, stock null) | All hold; 32 steps, callback on C, page ready after 700 ms | All hold; 1200 ms |
Why 700 ms with Caller starts late? In that schedule C reaches thenAccept only after F1 has completed the price, so C itself starts late, and its 300 ms of rendering come after that. The futures never make C wait there; the late start does. The tests behind the visualizer also explore every interleaving of the three threads (1,171 distinct states): the Futures version never breaks an invariant and never deadlocks, and the only difference between its possible endings is which thread ran the callback. The code panel leaves out try/finally around the lock and InterruptedException to stay short; the implementations below have both.
Variations
Blocking or callbacks
There are two ways to consume a future. Blocking: call get() (Java), result() (Python) or get() (C++) and wait. It is simple and reads top to bottom, but each waiting caller holds a thread. Callbacks: register what to do with the result (thenAccept, then, add_done_callback) and return. No thread waits, which is what lets one thread serve thousands of requests, but the logic is spread over callbacks. JavaScript has no blocking get() at all: a promise can only be consumed with then or await. Java's Future (Java 5) offered only get() and polling with isDone(); CompletableFuture (Java 8) added callbacks and composition.
Chaining
A continuation returns a new future, so steps chain without nesting. thenApply(f) transforms the value (price.thenApply(p -> p * 1.2)), thenCompose(f) continues with another asynchronous call that itself returns a future (userFuture.thenCompose(u -> fetchOrders(u.id()))), and the result is one flat future rather than a future of a future. JavaScript's then does both jobs: if the callback returns a promise, the chain waits for it. An error skips the remaining steps until a handler (exceptionally, handle, catch) deals with it, like an exception skipping lines until a catch.
fetchUser(id)
.then((user) => fetchOrders(user.id)) // returns a promise: the chain waits
.then((orders) => orders.filter((o) => o.open))
.then(render)
.catch(showError) // any failure above lands here
.finally(hideSpinner);Combining
| Wait for | Java (CompletableFuture) | JavaScript (Promise) | On failure |
|---|---|---|---|
| All of them | allOf(a, b) (then read each with join()) | Promise.all([a, b]) | Java completes when all are done, exceptionally if any failed; JS rejects as soon as one rejects |
| All, with each outcome | allOf(...) plus handle on each | Promise.allSettled([a, b]) | Never fails: you get { status, value } or { status, reason } per input |
| The first to succeed | no direct equivalent | Promise.any([a, b]) | Fails only if all fail, with an AggregateError |
| The first to finish | anyOf(a, b) | Promise.race([a, b]) | Settles like the first one to settle, success or failure |
| Two values together | a.thenCombine(b, (x, y) -> ...) | Promise.all([a, b]).then(([x, y]) => ...) | Fails if either fails |
concurrent.futures.wait (with ALL_COMPLETED, FIRST_COMPLETED or FIRST_EXCEPTION) and as_completed; asyncio has gather and wait.Timeouts and cancellation
A future that is never completed makes get() wait forever, so put a bound on every wait that crosses a network: get(2, SECONDS) and orTimeout (Java 9) in Java, result(timeout=2) in Python, wait_for in C++, and Promise.race with a timer or AbortSignal.timeout() for fetch in JavaScript. Cancelling is weaker than it sounds. Future.cancel(true) interrupts the worker thread of a FutureTask, which only helps if the task checks for interruption; CompletableFuture.cancel just completes the future with a CancellationException and does not interrupt work that is already running; a Python concurrent.futures future cannot be cancelled once it is running; a JavaScript promise has no cancel, so cancellation goes through an AbortController passed to the work. Timing out the wait and stopping the work are separate problems.
async/await
async/await (C# 5, JavaScript 2017, Python 3.5, Rust 1.39) is syntax over futures: const p = await price; suspends the function until the promise settles and turns a rejection into a thrown exception, so the code reads like the blocking version but no thread waits. Start the work before awaiting: const a = fetchA(); const b = fetchB(); await a; await b; overlaps the two calls, while await fetchA(); await fetchB(); runs them one after the other, which is the One by one version again.
In real code
| Where | What | Notes |
|---|---|---|
| Java | Future, FutureTask, ExecutorService.submit | Java 5. get() blocks and wraps failures in ExecutionException; get(timeout, unit) gives up; Java 19 added state(), resultNow() and exceptionNow() |
| Java | CompletableFuture | Java 8. Both sides in one object (complete, completeExceptionally); supplyAsync runs on the common ForkJoinPool unless you pass an executor; join() throws unchecked CompletionException instead |
| JavaScript | Promise, async/await | ES2015 and ES2017. then callbacks always run later as microtasks, even on a settled promise; Promise.withResolvers() (ES2024) hands out the resolve and reject functions, the promise side |
| Python | concurrent.futures.Future | Returned by ThreadPoolExecutor.submit; result(timeout) re-raises the worker's exception; add_done_callback runs in the completing thread, or at once if the future is already done |
| Python | asyncio.Future, asyncio.Task | For coroutines on one event loop; not thread-safe. asyncio.wrap_future bridges a concurrent.futures future into a loop |
| C++ | std::promise, std::future, std::async, std::packaged_task | C++11. get() works once and rethrows a stored exception; setting a promise twice throws future_error; destroying it unset stores broken_promise; no standard then |
| C# | Task<T>, TaskCompletionSource<T> | The task is the future, the completion source the promise; await (C# 5) consumes it |
| Scala | scala.concurrent.Future, Promise | Promise#success / failure complete it once; map, flatMap and recover chain on an ExecutionContext |
| Rust | the Future trait, async/await | Lazy: nothing runs until an executor (such as Tokio) polls it; dropping a future cancels it |
When to use it, and when not to
Reach for futures when
- Independent slow calls can overlap (fetch price and stock, query three services)
- The caller has other work to do while it waits
- A result must be handed to code that runs later or elsewhere
- Failures of background work must reach the code that uses the result
- Steps form a pipeline: fetch, then transform, then store, with one error path
Think twice when
- The call is fast or the next step needs its result right away: call it directly
- Many values arrive over time (prices ticking, messages): use a stream or Observer
- Each item must go to one of many workers: that is Producer-Consumer or Thread Pool
- Every
get()would block anyway: you added threads and gained nothing - The work must survive a crash: a future lives in memory; use a queue or a job table
Future & Promise vs similar patterns
| Pattern | Results | How the caller hears | Typical use |
|---|---|---|---|
| Future & Promise | Exactly one value or one error | Blocking get, or a continuation; completion happens once | One asynchronous call |
| Plain callbacks | One (by convention) | A function passed to the call (fetch(url, cb)) | Older async APIs; nests deeply ("callback hell") and errors are easy to drop |
| Observer | Many, over time | The subject calls every registered observer | Events and change notifications |
| Active Object | One per method call | Each call is queued for the object's own thread and returns a future | Making an object's methods asynchronous |
| Producer-Consumer | A stream of items | Consumers take items from a shared queue | Handing work between threads |
| Thread Pool | One per task | submit returns a future for the task | Running many tasks on a few threads |
Implementation
The product page from the visualizer with each language's standard futures: the price and the stock are fetched concurrently while the page renders, a continuation caches the price, and the stock fetch fails so the caller sees and handles the error. The total is about the longest fetch, not the sum. TypeScript uses promises with Promise.allSettled and a timeout built from Promise.race; Java uses CompletableFuture.supplyAsync on a fixed thread pool with orTimeout; Python uses a ThreadPoolExecutor with add_done_callback; C++ uses std::async, whose futures rethrow the task's exception from get(). Standard C++ has no then, so there is no callback in that version.
import time
from concurrent.futures import ThreadPoolExecutor
def fetch_price():
time.sleep(0.4) # the price service answers after 400 ms
return 25
def fetch_stock():
time.sleep(0.5)
raise ConnectionError("stock service timed out")
def render_page():
time.sleep(0.3) # the caller's own work
def main():
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=2) as pool:
# Both fetches start now, on the pool's threads.
price = pool.submit(fetch_price)
stock = pool.submit(fetch_stock)
# Runs in the thread that completes the future, or right here
# if the future is already done.
price.add_done_callback(
lambda f: print("cached price", f.result()))
render_page() # overlaps the two fetches
p = price.result(timeout=2) # blocks only if not ready yet
try:
s = stock.result(timeout=2) # re-raises the worker's error
except ConnectionError as e:
print("stock failed:", e)
s = "unknown"
ms = (time.perf_counter() - start) * 1000
print(f"price {p}, stock {s} after {ms:.0f} ms") # about 500
if __name__ == "__main__":
main()Key takeaways
- A future is a handle to a result that is not ready yet; the promise is the write side that completes it once, with a value or an exception.
- Start every independent call before waiting on any: in the visualizer the page is ready after 500 ms (the longest fetch) instead of 1200 ms one by one.
get()waits only if it must, and never returns before completion; built by hand it is a lock, a condition and awhile (state == PENDING)loop.- The future carries failures:
get()rethrows (wrapped inExecutionExceptionin Java), and a rejected promise skips to the nextcatch. Plain fields lose the exception and shownull. - Continuations (
thenAccept,then,add_done_callback) avoid blocking; in Java and Python they run on the completing thread, or on the caller if the future is already done. - Combine with
allOf/Promise.all,allSettled,anyandrace, and put a timeout on every wait that crosses a network.
Common pitfalls
- Calling a blocking
get()on the thread that is supposed to complete the future (the only thread of a pool, or an event loop): it waits for itself and deadlocks. - Swallowed failures: an exception stored in a future nobody calls
get()on, athenchain withoutcatch, or a fire-and-forget promise. Node.js ends the process on an unhandled rejection by default since version 15. - Assuming which thread runs a callback: a non-async
thenApplymay run on the completing worker or on the caller, so slow or thread-bound code (UI updates, thread-local state) needs an explicit executor (thenApplyAsync(f, executor)). - Waiting without a timeout: if the remote call hangs, the future never completes and every
get()on it hangs too. - Awaiting in sequence by accident:
await a(); await b();does not overlap the calls; start both first, then await, or usePromise.all.
Interview tips
- Define the two sides clearly: the future is read-only for consumers, the promise (or
complete) is for the producer, and completion happens once. - Be ready to build one from a lock and a condition variable, and to explain why
get()waits in awhileloop and why callbacks run outside the lock. - Know the combinators and their failure behavior:
Promise.allrejects on the first failure,allSettlednever rejects,anyneeds one success,racetakes the first to settle;thenComposeflattens nested futures. - Mention the practical concerns: timeouts, cancellation not stopping the work, which thread runs callbacks, and unhandled rejections.
Real-world applications
- Web backends fanning out to several services for one page and combining the answers.
- Executors and thread pools:
submitreturns a future for each task. - Browser and Node.js code: every
fetch, file read and timer-based wait returns a promise. - RPC and HTTP clients that return futures for responses, such as gRPC's future stubs in Java and
java.net.http.HttpClient.sendAsync. - Caches that store the future of a value being loaded, so concurrent requests for the same key wait on one load instead of starting many.
Test yourself
In the visualizer's Futures version with Caller first, C calls price.get() while the price is still PENDING. What happens?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.