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.

Watch lesson4:48

Where it shows up

The same pattern appears across everyday software.

  • Java HttpClient

    sendAsync returns at once with a CompletableFuture of the response, which completes when the response becomes available.

  • AWS SDK for Java 2

    Asynchronous clients return CompletableFuture objects. Methods have the same signatures as the synchronous ones otherwise.

  • Apache Kafka producer

    send is asynchronous: it adds the record to a buffer, returns immediately with a Future of the metadata, and a second form takes a callback.

  • JavaScript Promise

    Part of the language. The Promises/A+ specification, from which the then rules come, demands that callbacks run only after the current code has ended and at most once.

  • Python concurrent.futures

    Its documentation shows how a pool deadlocks when a callable waits for the result of another future, with one worker waiting for itself.

  • C++ standard library

    promise and future are two objects. A promise that is abandoned stores the error broken_promise. The future of std::async may wait in its destructor.

  • .NET TaskCompletionSource

    Documented as the producer side of a Task that is not bound to a delegate, with the consumer side available through its Task property.

  • Go singleflight

    golang.org/x/sync/singleflight suppresses duplicate calls: callers with the same key share one execution and its result.

  • Caffeine AsyncCache

    A cache variant that computes entries on an Executor and stores CompletableFutures, so that later callers of a key find the running load.

  • Guava ListenableFuture

    Each listener is registered together with an executor, which is used to run it when the computation is complete.