Future and promise
medium 50 minA future is a placeholder for a result that comes later, a promise is the one right to put it there.
Video lesson · Chapter 1 of 6
Make a prediction
Future and promise
1:05Reel
Theory
Read or listen first. About 2 min.
What it is
A future stands for a value that does not exist yet. It starts pending and is settled once: fulfilled with a value, or rejected with an error. Readers can wait for it, or leave a function that runs when it is settled.
A promise is the other end: the object, or the pair of functions, that settles it. Whoever holds the promise owns the outcome. Languages name the two ends differently, but the two ends are always there.
An executor is a third role: it decides who does the work. The future does not care whether the value comes from a thread, from the network, or from a person who presses a button.
Why it exists
Waiting is expensive if a thread does it. With a future, the thread that asked can go on, and the result finds its way later.
Independent calls can overlap. Three calls of 200 ms take 600 ms one after the other, and about 200 ms if all three are started before the first wait.
Plain callbacks can do both, but they cannot be returned, stored, combined or limited in time. A future turns the result that will come into a value you can handle.
Errors follow the same way as values. One handler at the end of a chain sees what went wrong in any step.
A short history
1976
Daniel Friedman and David Wise propose the term promise.
1977
Henry Baker and Carl Hewitt describe futures in The Incremental Garbage Collection of Processes.
1988
Barbara Liskov and Liuba Shrira publish Promises: linguistic support for efficient asynchronous procedure calls.
2004
Java 5 adds Future and ExecutorService.
2011
C++11 adds std::future, std::promise and std::async. Python 3.2 brings concurrent.futures, proposed in PEP 3148.
2014
Java 8 adds CompletableFuture and CompletionStage.
2015
ECMAScript 2015 makes Promise part of JavaScript. Python 3.5 brings async and await, proposed in PEP 492.
Words to know
- Pending
- Not settled yet.
- Settled
- Fulfilled or rejected. Never changes again.
- Fulfilled
- Settled with a value. Also resolved or completed.
- Rejected
- Settled with an error. Also failed or completed exceptionally.
- Executor
- Runs tasks: a thread, a pool, an event loop.
- Continuation
- A function that runs when a future is settled.
- Composition
- Making a new future from old ones.
- Flatten
- Following the future that a step returned, instead of nesting it.
- Broken promise
- A promise that is gone without having been settled.
- Single flight
- Many callers for one key share one load.
- Cooperative cancellation
- The work looks at a request to stop and ends itself.
- Structured concurrency
- Tasks cannot outlive the block that started them.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Submit. Ask for work, get a pending future at once
Understand it
Start here
An empty case with a number
Asha orders a hat. It takes an hour. Standing at the counter for an hour would be silly. So the hat maker reserves an empty glass case, number 42, and gives Asha a slip with that number. Asha can leave, come back, or send a friend with a copy of the slip. When the hat is finished it goes into the case, and the case is sealed. The slip is a future. The right to fill the case is a promise.
Empty, then sealed with a hat or with a note, and never anything else after that.
Who takes part
Future
The read side. Is it done? Wait for it. Call me when it is. Names:
Future,CompletableFuture,std::future, JavaScript'sPromise.Promise
The write side. Complete with a value or with an error. Names:
complete(),resolveandreject,std::promise,TaskCompletionSource.Executor
Decides who does the work: a pool of threads, an event loop, a device.
Callback
What should happen with the result:
thenApply,then,await,add_done_callback.
Why
What goes wrong without it
A page needs a user, the orders and a price. Each takes 100 ms on the network. Version one waits for each in turn and holds a thread all the time. Version two hands over callbacks.
getUser(userId, (user) => { getOrders(user.id, (orders) => { getItems(orders[0].id, (items) => { getPrice(items[0].id, (price) => { console.log(price); // four levels deep, no error handled }); }); });});The design that hurts
1/3The page keeps the state
Half results live in fields. Which are set depends on which answer has come.
uses
getUser(userId) .then((user) => getOrders(user.id)) .then((orders) => getItems(orders[0].id)) .then((items) => getPrice(items[0].id)) .then((price) => console.log(price)) .catch((error) => handleError(error));async function priceFor(userId) { const user = await getUser(userId); const orders = await getOrders(user.id); const items = await getItems(orders[0].id); return getPrice(items[0].id); // an error in any line rejects the result}Three styles
| Wait in place | Callbacks | Futures | |
|---|---|---|---|
| Thread while waiting | Held | Free | Free, unless you call get |
| Errors | Exceptions | By hand at each level | Travel along to one handler |
| Combine two results | One after the other | Counters and flags | all, thenCombine |
| Pass it on | The value | Not possible | The future is a value |
| Called how often | once | up to the API | settles once, always |
The idea
Two sides of one box
Future and promise in general
1/4The client reads
It holds a future. No method on it can set a value.
useshas (lives on)
Three states, two arrows
Order 42 in the asynchronous coffee shop
How it works
- 1
Submit
The client hands a task to an executor, or calls an asynchronous function.
- 2
Get a future
At once, in the pending state.
- 3
Execute
A worker thread, an event loop or a remote machine does the work.
- 4
Complete
The promise is fulfilled or rejected. Waiters wake and callbacks run.
Read
Two ways to get the result
Callback or await
- No thread waits
- Steps are written where they belong
- Needs care: on which thread does it run?
- The normal way in servers and user interfaces
Blocking get
- Simple to read
- Holds a thread until the result is there
- Inside a pool it can stop the whole pool
- Fine at the edge: in main, in a test, in a script
The operations in four libraries
| Want | Java | Python | JavaScript | C++ |
|---|---|---|---|---|
| Start | supplyAsync(work, pool) | pool.submit(work), create_task | new Promise(...), async | std::async |
| Wait | get(1, SECONDS), join() | result(timeout), await | await | get(), wait_for |
| Look | isDone() | done() | no call for it | wait_for(0s) |
| Change the value | thenApply | a line after await | then | by hand |
| Next asynchronous step | thenCompose | another await | then returning a promise | by hand |
| Two together | thenCombine | gather | Promise.all | two gets |
| All | allOf | gather, TaskGroup | Promise.all | a loop of gets |
| First | anyOf | wait(FIRST_COMPLETED) | race, any | by hand |
| Error | exceptionally, handle | try around await | catch | try around get |
| Complete by hand | complete(v) | set_result(v) | resolve(v) | set_value(v) |
| Cancel | cancel(true) | task.cancel() | AbortSignal | no |
Combine
Four shapes
Chain, all, race, combine
import asyncio, timeasync def fetch(name): await asyncio.sleep(0.05) return nameasync def one_by_one(): return [await fetch("A"), await fetch("B"), await fetch("C")]async def together(): return await asyncio.gather(fetch("A"), fetch("B"), fetch("C"))for work in (one_by_one, together): start = time.perf_counter() result = asyncio.run(work()) print(work.__name__, result, round((time.perf_counter() - start) * 20), "x 50 ms")All, all settled, race, any
| Settles when | With | On an error | |
|---|---|---|---|
| all | All have values | A list in the order given | Rejects at the first error, the others run on |
| allSettled | All are settled | A list of outcomes | Is never rejected |
| race | The first is settled | That value or error | A fast error wins too |
| any | The first has a value | That value | Rejects only if all failed |
allOf is the exception: it waits for all of them even if one has failed, and it carries no values.CompletableFuture<CompletableFuture<Orders>> nested = fetchUser(id).thenApply(user -> fetchOrders(user)); // not what you wantCompletableFuture<Orders> flat = fetchUser(id).thenCompose(user -> fetchOrders(user)); // follows the inner oneErrors
An error travels until somebody takes it
A value lane and an error lane
CompletableFuture<String> f = CompletableFuture.supplyAsync(this::risky);f.exceptionally(e -> "default"); // result thrown awayf.join(); // still throwsString ok = CompletableFuture.supplyAsync(this::risky) .exceptionally(e -> "default") .join(); // the new futureFit
When to use it and when not
Use it when
- Input and output that take time: network, files, database
- Several independent calls can run together
- A user interface must stay responsive
- Steps depend on each other and should read as a chain
- A result is needed by several parts
- Work runs in the background and its end matters
- Services call services
Leave it when
- The call is fast and local: a plain function is clearer
- You call get right after starting: that is a plain call with extra cost
- Many values over time: a stream, queue or observer
- Nobody looks at the result or the error: then say so, and log it
- You only need the order of steps in one thread
- A small script without anything to wait for
A page needs profile, orders and adverts. Each takes 200 ms. Adverts may be missing. What do you write?
BreaksThree awaits, one after the other
- How
await profile(); await orders(); await ads()- Limit
- 600 ms, and if adverts fail the page fails.
- Choose when
- Only if each needs the one before.
Worksall of the three
- How
- Start all,
await Promise.all([...]). - Limit
- 200 ms. But the advert error still rejects the whole page.
- Choose when
- When all are required.
Strongall, with adverts recovered and limited
- How
- Adverts get their own timeout and a recover to an empty list, then all three are combined. Profile and orders stay required.
- Limit
- Decide per part what required means.
- Choose when
- Any page built from several services.
Summary
The whole topic in one minute.
A future is read, a promise is written once. Pending becomes fulfilled or rejected and stays so. Start independent work first and wait afterwards. Use thenApply for values, thenCompose for futures, and one handler at the end.
Inside: change the state and take the list of callbacks in one step, call them after the lock. Every combinator is one new promise, a callback on each input and a count.
In depth: where callbacks run, pools that starve because tasks wait for tasks, timeouts that end the waiting and tokens that end the work, one load per key, errors with an owner, and tasks that belong to a block.
- Future reads, promise writes once. Pending, then fulfilled or rejected.
- Start independent work first, wait afterwards.
- thenApply for a value, thenCompose for a future.
- Errors travel. Take them once, at the end, on the new future.
- Do not block on a future inside the pool that must complete it.
- A timeout ends the waiting, not the work. Cancel needs the help of the work.
- A promise that nobody settles is a waiter that never wakes.