AlgoViz

Future and promise

medium 50 min

A 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

0:00 / 4:48

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

  1. 1976

    Daniel Friedman and David Wise propose the term promise.

  2. 1977

    Henry Baker and Carl Hewitt describe futures in The Incremental Garbage Collection of Processes.

  3. 1988

    Barbara Liskov and Liuba Shrira publish Promises: linguistic support for efficient asynchronous procedure calls.

  4. 2004

    Java 5 adds Future and ExecutorService.

  5. 2011

    C++11 adds std::future, std::promise and std::async. Python 3.2 brings concurrent.futures, proposed in PEP 3148.

  6. 2014

    Java 8 adds CompletableFuture and CompletionStage.

  7. 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.

Step 1 of 3

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.

The glass case
NOT YET42

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's Promise.

  • Promise

    The write side. Complete with a value or with an error. Names: complete(), resolve and reject, 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.

JavaScript
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      });    });  });});
Callbacks inside callbacks. The shape moves to the right, and where are the errors?

The design that hurts

PricePage- user, orders, items- failed: boolean- missing: int+ onUser()+ onOrders()+ onItems()+ onPrice()+ onError()

1/3The page keeps the state

Half results live in fields. Which are set depends on which answer has come.

uses

The missing thing is an object for the result that is not there yet.
JavaScript
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}
The same work with promises, and with await. One error handler for all steps.

Three styles

Wait in placeCallbacksFutures
Thread while waitingHeldFreeFree, unless you call get
ErrorsExceptionsBy hand at each levelTravel along to one handler
Combine two resultsOne after the otherCounters and flagsall, thenCombine
Pass it onThe valueNot possibleThe future is a value
Called how oftenonceup to the APIsettles once, always

The idea

Two sides of one box

Future and promise in general

readsClient+ asks, reads«interface»Future<T>+ get(timeout): T+ isDone(): boolean+ then(fn): Future<U>+ cancel(): boolean

1/4The client reads

It holds a future. No method on it can set a value.

useshas (lives on)

In Java's CompletableFuture three of these boxes are one class. The roles remain.

Three states, two arrows

There is no arrow back and no arrow across. Fulfilled and rejected together are called settled. Some libraries add running, which belongs to the task and not to the result.

Order 42 in the asynchronous coffee shop

Submit, get a future, the work runs, the result arrives. Four steps, and the customer waits in none of them.

How it works

  1. 1

    Submit

    The client hands a task to an executor, or calls an asynchronous function.

  2. 2

    Get a future

    At once, in the pending state.

  3. 3

    Execute

    A worker thread, an event loop or a remote machine does the work.

  4. 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

WantJavaPythonJavaScriptC++
StartsupplyAsync(work, pool)pool.submit(work), create_tasknew Promise(...), asyncstd::async
Waitget(1, SECONDS), join()result(timeout), awaitawaitget(), wait_for
LookisDone()done()no call for itwait_for(0s)
Change the valuethenApplya line after awaitthenby hand
Next asynchronous stepthenComposeanother awaitthen returning a promiseby hand
Two togetherthenCombinegatherPromise.alltwo gets
AllallOfgather, TaskGroupPromise.alla loop of gets
FirstanyOfwait(FIRST_COMPLETED)race, anyby hand
Errorexceptionally, handletry around awaitcatchtry around get
Complete by handcomplete(v)set_result(v)resolve(v)set_value(v)
Cancelcancel(true)task.cancel()AbortSignalno

Combine

Four shapes

Chain, all, race, combine

Chain when one needs the other. Everything else starts at once.
Python
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")
Three calls of 50 ms. The two versions differ in one thing: when the second call is started.
Edit and run it in your browser

All, all settled, race, any

Settles whenWithOn an error
allAll have valuesA list in the order givenRejects at the first error, the others run on
allSettledAll are settledA list of outcomesIs never rejected
raceThe first is settledThat value or errorA fast error wins too
anyThe first has a valueThat valueRejects only if all failed
Java's allOf is the exception: it waits for all of them even if one has failed, and it carries no values.
Java
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 one
thenApply or thenCompose? If the step returns a future itself, thenApply gives a future inside a future.

Errors

An error travels until somebody takes it

A value lane and an error lane

Like exceptions: steps in between are skipped, and after a recover the value lane goes on.
Java
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 future
The mistake in many examples: exceptionally returns a new future. Whoever joins the old one still gets the error.

Fit

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.

Sources