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

See it run

Who holds the future, who settles it, and what runs when.

Operations

Coffee shop

Order 42 from submit to the first sip.

Step 1 of 8

Place the order

customerCallerdoesordersticket 42FuturestatependingvaluenonepoolExecutorqueue1 taskbaristaWorkerdoesidlesubmit(latte)

The caller asks the pool and does not wait for coffee.

Step 1: Place the order

def order(drink):    promise = Promise()    pool.execute(lambda: promise.complete(make(drink)))    return promise.futureticket = order("latte")ticket.done()read_a_book()coffee = ticket.get(timeout=300)
Watch
state
Result
The customer never waits

done() looks, get() waits. Here get comes when the value is there.

In the real world

The same future and promise doing real jobs. Pick one and step through it.

Two workers, two tasks, each waits for a task in the queue.

Step 1 of 3

Two outer tasks

worker 1Threadrunsouter 1worker 2Threadrunsouter 2queueQueueholdsnothing

Both workers are busy.

Step 1: Two outer tasks

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Waiting one after the other

    major

    Independent calls take the sum instead of the longest.

    Wrong
    a = await fetch_a()b = await fetch_b()
    Right
    a, b = await asyncio.gather(fetch_a(), fetch_b())
  • get inside the pool

    critical

    The worker waits for a task that needs a worker.

    Wrong
    def outer():    return pool.submit(inner).result()
    Right
    return then_compose(start_inner(), finish)# or: a second pool for inner tasks
  • Callbacks under the lock

    critical

    Unknown code may call back or wait.

    Wrong
    with lock:    self.value = v    for call in self.later: call(v)
    Right
    with lock:    self.value = v    later, self.later = self.later, []for call in later: call(v)
  • Testing the value

    critical

    0, empty text and None are results too.

    Wrong
    if self.result:    callback(self.result)
    Right
    if self.state != "pending":    callback(self.value)
  • Recovering on the side

    major

    The default is in a new future that nobody reads.

    Wrong
    f = fetch()recover(f, lambda e: "default")f.get()
    Right
    f = recover(fetch(), lambda e: "default")f.get()
  • An error that nobody reads

    critical

    The task failed, the program says done.

    Wrong
    pool.submit(save, row)print("done")
    Right
    job = pool.submit(save, row)job.result()        # or log it in a callback

Interview tips

  • Two sides

    • Keep the promise.
    • Give away the future.
    • Settle once.
  • Compose

    • Start first, wait later.
    • Value: then. Future: compose.
    • One handler at the end.
  • Threads

    • Know where callbacks run.
    • Never block in the pool.
    • Complete after the lock.
  • Every promise ends

    • With a deadline.
    • On a closed connection.
    • Also when you drop it.
  • In depth

    • Token for the work.
    • One load per key.
    • Tasks belong to a block.