Patterncore
Future as a design pattern
Also called future pattern, future, promise, placeholder for a later result.
A call starts slow work and returns a future at once. The caller does other work and asks the future for the value when it needs it, and it waits only if the value is not ready.
- Family
- concurrency
- Intent
- Let a caller start a computation without waiting for it, and give the caller an object that delivers the result, or the error, when the computation completes.
- Also called
- Promise, Deferred
Intent
A future is an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is not yet complete.1 As a design pattern, a call starts the computation and returns a future at once. The caller continues with other work and asks the future for the value only when it needs it.
This page states the pattern. The page futures describes the mechanism and how each language provides it.
Problem
A caller needs the results of several slow calls, for example three price lookups on other machines. If each call blocks until its result is ready, the calls run one after another, and the caller can do nothing else while it waits. If the calls run on other threads with no return value, the caller needs a separate way to collect each result and each error.
Solution
Each call starts the work, for example on a thread pool, and returns a future. A future represents the result of an asynchronous computation, and it has methods to check if the computation is complete, to wait for its completion, and to retrieve the result.2 The result can only be retrieved when the computation has completed, and the call that retrieves it blocks if necessary until it is ready.2
caller future worker thread
│ submit(lookup, "apple") │ │
├──────────────────────────► │ ── start lookup ─────► │
│ ◄── future (not done) ──── │ │
│ (other work) │ │ (runs lookup)
│ │ ◄── set result 12 ──── │
│ result() ────────────────► │ │
│ ◄── 12 ─────────────────── │ │
When the two sides are distinguished, the future is a read-only placeholder view of a variable, and the promise is a writable, single assignment container which sets the value of the future.1 The worker holds the promise side, and the caller holds the future side.
Example
The caller starts three price lookups, and each call returns a future at once. No future is done right after the calls, because each lookup waits at a barrier until all three lookups and the caller arrive. That shows that the three lookups ran at the same time while the caller was free. Then the caller reads the three results in the order of the calls.
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
The examples for each language show the same program.
import threading
from concurrent.futures import ThreadPoolExecutor
PRICES = {"apple": 12, "bread": 7, "cheese": 30}
# The lookups wait here with the caller, so the output does not depend on timing.
meeting = threading.Barrier(4, timeout=5)
def lookup(item):
meeting.wait() # returns when all 3 lookups and the caller are here
return PRICES[item]
with ThreadPoolExecutor(max_workers=3) as pool:
# Each call returns a future at once. The lookup runs on a pool thread.
futures = [pool.submit(lookup, item) for item in PRICES]
print("lookups started:", len(futures))
print("done right after the calls:", any(f.done() for f in futures))
meeting.wait() # the caller is free to do other work here
print("all three lookups ran at once:", not meeting.broken)
prices = [f.result() for f in futures] # wait for each result
print("prices:", prices)
print("total:", sum(prices))
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: stdlib.
Executor.submitreturns aconcurrent.futures.Futureat once;done()checks it andresult()waits for the value.
#include <chrono>
#include <condition_variable>
#include <future>
#include <iostream>
#include <map>
#include <mutex>
#include <string>
#include <vector>
// The lookups wait here with the caller, so the output does not depend on timing.
class Meeting {
public:
explicit Meeting(int parties) : left_(parties) {}
bool arrive_and_wait() {
std::unique_lock<std::mutex> lock(m_);
if (--left_ == 0) cv_.notify_all();
return cv_.wait_for(lock, std::chrono::seconds(5), [&] { return left_ <= 0; });
}
private:
std::mutex m_;
std::condition_variable cv_;
int left_;
};
int main() {
std::vector<std::string> items = {"apple", "bread", "cheese"};
std::map<std::string, int> prices = {{"apple", 12}, {"bread", 7}, {"cheese", 30}};
Meeting meeting(4);
// Each call returns a future at once. The lookup runs on its own thread.
std::vector<std::future<int>> futures;
for (const auto& item : items) {
futures.push_back(std::async(std::launch::async, [&, item] {
meeting.arrive_and_wait(); // returns when all 3 lookups and the caller are here
return prices.at(item);
}));
}
std::cout << "lookups started: " << futures.size() << "\n";
bool any_done = false;
for (auto& f : futures) {
if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) any_done = true;
}
std::cout << "done right after the calls: " << (any_done ? "True" : "False") << "\n";
bool met = meeting.arrive_and_wait(); // the caller is free to do other work here
std::cout << "all three lookups ran at once: " << (met ? "True" : "False") << "\n";
std::vector<int> results;
for (auto& f : futures) results.push_back(f.get()); // wait for each result
std::cout << "prices: [";
int total = 0;
for (size_t i = 0; i < results.size(); i++) {
std::cout << (i ? ", " : "") << results[i];
total += results[i];
}
std::cout << "]\n";
std::cout << "total: " << total << "\n";
}
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: stdlib.
std::asyncwithstd::launch::asyncreturns astd::future<int>at once;wait_forwith a time of zero checks it andget()waits for the value.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws Exception {
String[] items = {"apple", "bread", "cheese"};
Map<String, Integer> prices = Map.of("apple", 12, "bread", 7, "cheese", 30);
// The lookups wait here with the caller, so the output does not depend on timing.
CyclicBarrier meeting = new CyclicBarrier(4);
ExecutorService pool = Executors.newFixedThreadPool(3);
// Each call returns a future at once. The lookup runs on a pool thread.
List<Future<Integer>> futures = new ArrayList<>();
for (String item : items) {
futures.add(pool.submit(() -> {
meeting.await(5, TimeUnit.SECONDS); // returns when all 3 lookups and the caller are here
return prices.get(item);
}));
}
System.out.println("lookups started: " + futures.size());
boolean anyDone = futures.stream().anyMatch(Future::isDone);
System.out.println("done right after the calls: " + (anyDone ? "True" : "False"));
meeting.await(5, TimeUnit.SECONDS); // the caller is free to do other work here
System.out.println("all three lookups ran at once: " + (meeting.isBroken() ? "False" : "True"));
List<Integer> results = new ArrayList<>();
for (Future<Integer> f : futures) results.add(f.get()); // wait for each result
pool.shutdown();
System.out.println("prices: " + results);
System.out.println("total: " + results.stream().mapToInt(Integer::intValue).sum());
}
}
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: stdlib.
ExecutorService.submitreturns aFuture<Integer>at once;isDone()checks it andget()waits for the value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
string[] items = { "apple", "bread", "cheese" };
var prices = new Dictionary<string, int> { ["apple"] = 12, ["bread"] = 7, ["cheese"] = 30 };
// The lookups wait here with the caller, so the output does not depend on timing.
var meeting = new Barrier(4);
// Each call returns a task at once. The lookup runs on its own thread.
var tasks = items.Select(item => Task.Factory.StartNew(() =>
{
meeting.SignalAndWait(TimeSpan.FromSeconds(5)); // returns when all 3 lookups and the caller are here
return prices[item];
}, TaskCreationOptions.LongRunning)).ToList();
Console.WriteLine("lookups started: " + tasks.Count);
Console.WriteLine("done right after the calls: " + (tasks.Any(t => t.IsCompleted) ? "True" : "False"));
bool met = meeting.SignalAndWait(TimeSpan.FromSeconds(5)); // the caller is free to do other work here
Console.WriteLine("all three lookups ran at once: " + (met ? "True" : "False"));
var results = tasks.Select(t => t.Result).ToList(); // wait for each result
Console.WriteLine("prices: [" + string.Join(", ", results) + "]");
Console.WriteLine("total: " + results.Sum());
}
}
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: stdlib.
Task.Factory.StartNewreturns aTask<int>at once;IsCompletedchecks it andResultwaits for the value.
const PRICES = { apple: 12, bread: 7, cheese: 30 };
// The lookups wait here with the caller, so the output does not depend on timing.
let arrived = 0;
let openMeeting;
const meeting = new Promise((resolve) => (openMeeting = resolve));
function arrive() {
arrived++;
if (arrived === 4) openMeeting();
return meeting;
}
let settled = 0;
async function lookup(item) {
await arrive(); // continues when all 3 lookups and the caller are here
return PRICES[item];
}
async function main() {
// Each call returns a promise at once.
const futures = Object.keys(PRICES).map((item) => lookup(item));
for (const f of futures) f.then(() => settled++);
console.log("lookups started:", futures.length);
console.log("done right after the calls:", settled > 0 ? "True" : "False");
await arrive(); // the caller is free to do other work here
console.log("all three lookups ran at once:", arrived === 4 ? "True" : "False");
const prices = await Promise.all(futures); // wait for each result
console.log("prices: [" + prices.join(", ") + "]");
console.log("total:", prices.reduce((a, b) => a + b, 0));
}
main();
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: native. An
asyncfunction returns aPromiseat once, andawaitandPromise.allwait for the values. The lookups are tasks on one event loop, so they wait at the same point but do not run in parallel.
const PRICES: Record<string, number> = { apple: 12, bread: 7, cheese: 30 };
// The lookups wait here with the caller, so the output does not depend on timing.
let arrived: number = 0;
let openMeeting: () => void = () => {};
const meeting = new Promise<void>((resolve) => (openMeeting = resolve));
function arrive(): Promise<void> {
arrived++;
if (arrived === 4) openMeeting();
return meeting;
}
let settled: number = 0;
async function lookup(item: string): Promise<number> {
await arrive(); // continues when all 3 lookups and the caller are here
return PRICES[item];
}
async function main(): Promise<void> {
// Each call returns a promise at once.
const futures = Object.keys(PRICES).map((item) => lookup(item));
for (const f of futures) f.then(() => settled++);
console.log("lookups started:", futures.length);
console.log("done right after the calls:", settled > 0 ? "True" : "False");
await arrive(); // the caller is free to do other work here
console.log("all three lookups ran at once:", arrived === 4 ? "True" : "False");
const prices = await Promise.all(futures); // wait for each result
console.log("prices: [" + prices.join(", ") + "]");
console.log("total:", prices.reduce((a, b) => a + b, 0));
}
main();
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: native. An
asyncfunction returns aPromise<number>at once, andawaitandPromise.allwait for the values. The lookups are tasks on one event loop, so they wait at the same point but do not run in parallel.
package main
import (
"fmt"
"strings"
"sync"
)
var prices = map[string]int{"apple": 12, "bread": 7, "cheese": 30}
// lookup returns a future at once: a channel that receives the one result.
func lookup(item string, arrived *sync.WaitGroup, release <-chan struct{}) <-chan int {
future := make(chan int, 1)
go func() {
arrived.Done()
<-release // wait until all 3 lookups and the caller are here
future <- prices[item]
}()
return future
}
func ready(future <-chan int) bool {
return len(future) > 0
}
func main() {
items := []string{"apple", "bread", "cheese"}
// The lookups wait for the caller, so the output does not depend on timing.
var arrived sync.WaitGroup
arrived.Add(len(items))
release := make(chan struct{})
var futures []<-chan int
for _, item := range items {
futures = append(futures, lookup(item, &arrived, release))
}
fmt.Println("lookups started:", len(futures))
anyDone := false
for _, f := range futures {
anyDone = anyDone || ready(f)
}
fmt.Println("done right after the calls:", map[bool]string{true: "True", false: "False"}[anyDone])
arrived.Wait() // the caller is free to do other work here
close(release)
fmt.Println("all three lookups ran at once: True")
var results []string
total := 0
for _, f := range futures {
p := <-f // wait for each result
results = append(results, fmt.Sprint(p))
total += p
}
fmt.Println("prices: [" + strings.Join(results, ", ") + "]")
fmt.Println("total:", total)
}
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: idiom. A function starts a goroutine and returns a channel with a buffer of one. A receive from the channel waits for the value, and
lenof the channel shows whether the value is there.
use std::collections::HashMap;
use std::sync::{Arc, Barrier};
use std::thread;
fn main() {
let items = ["apple", "bread", "cheese"];
let prices: Arc<HashMap<&str, i32>> = Arc::new(HashMap::from([("apple", 12), ("bread", 7), ("cheese", 30)]));
// The lookups wait here with the caller, so the output does not depend on timing.
let meeting = Arc::new(Barrier::new(4));
// Each call returns a handle at once. The lookup runs on its own thread.
let futures: Vec<thread::JoinHandle<i32>> = items
.iter()
.map(|&item| {
let (prices, meeting) = (Arc::clone(&prices), Arc::clone(&meeting));
thread::spawn(move || {
meeting.wait(); // returns when all 3 lookups and the caller are here
prices[item]
})
})
.collect();
println!("lookups started: {}", futures.len());
let any_done = futures.iter().any(|f| f.is_finished());
println!("done right after the calls: {}", if any_done { "True" } else { "False" });
meeting.wait(); // the caller is free to do other work here
println!("all three lookups ran at once: True");
let results: Vec<i32> = futures.into_iter().map(|f| f.join().unwrap()).collect(); // wait for each result
println!("prices: {:?}", results);
println!("total: {}", results.iter().sum::<i32>());
}
lookups started: 3
done right after the calls: False
all three lookups ran at once: True
prices: [12, 7, 30]
total: 49
- Verdict: stdlib.
thread::spawnreturns aJoinHandle<i32>at once;is_finishedchecks it andjoinwaits for the value.
Consequences
Benefits:
- The caller does not wait at the call. In the example of the Java
Futuredocumentation, the caller submits a search and then has the comment "do other things while searching" before it callsget.2 - The result and the error travel together. In Python, if the call raised an exception,
result()will raise the same exception.3 - The caller decides when to wait. Python's
result(timeout)waits up to the timeout and then raises aTimeoutError.3
Liabilities:
- Deadlocks can occur when the callable associated with a future waits on the results of another future.3 In a pool with a fixed number of threads, a task that waits for a future of the same pool can block a thread that the other task needs.
- Work can become useless. Baker and Hewitt describe futures which were thought to be relevant when they were created but become irrelevant because the program ignores them.4 In Java, cancellation is performed by the
cancelmethod, but once a computation has completed, the computation cannot be cancelled.2 - A blocking wait can hide where the work runs. In C++, if the future came from
std::async(), a blocking wait without a timeout may run the function on the waiting thread.1
This program waits for each future right after the call that makes it. The results are correct, but the lookups never overlap:
This code runs but gives a wrong answer on purpose.
import threading
import time
from concurrent.futures import ThreadPoolExecutor
PRICES = {"apple": 12, "bread": 7, "cheese": 30}
lock = threading.Lock()
running = 0
most_running = 0
def lookup(item):
global running, most_running
with lock:
running += 1
most_running = max(most_running, running)
time.sleep(0.05) # a slow lookup
with lock:
running -= 1
return PRICES[item]
with ThreadPoolExecutor(max_workers=3) as pool:
# Wrong: wait for each future right after the call that makes it.
prices = [pool.submit(lookup, item).result() for item in PRICES]
print("prices:", prices)
print("most lookups running at once:", most_running)
prices: [12, 7, 30]
most lookups running at once: 1
Start all the calls first, keep the futures in a list, and then read the results, as the example does.
When not to use it
Do not use a future when the caller needs the value at once and has no other work to do. A plain call gives the same result with less code. Do not use one future for a stream of many values. A queue in the producer-consumer pattern, or a channel, fits that case. Do not let tasks in a small, fixed pool wait on futures of the same pool, because of the deadlock above. The fork-join page shows a pool for tasks that wait for their subtasks.
Variants and related patterns
- Explicit and implicit futures. With an explicit future, the user must call a function to obtain the value, such as the
getmethod ofFuturein Java.1 With an implicit future, any use of the future obtains its value, as if it were an ordinary reference.1 The original Baker and Hewitt paper described implicit futures.1 With an explicit future, the call that reads the value is also where the error of the computation appears:
from concurrent.futures import ThreadPoolExecutor
PRICES = {"apple": 12}
def lookup(item):
return PRICES[item] # raises KeyError for an unknown item
with ThreadPoolExecutor(max_workers=2) as pool:
ok = pool.submit(lookup, "apple")
bad = pool.submit(lookup, "caviar")
print("price of apple:", ok.result())
try:
bad.result() # the exception of the call comes back here
except KeyError as e:
print("lookup of caviar raised:", repr(e))
price of apple: 12
lookup of caviar raised: KeyError('caviar')
- Callbacks on completion. The caller attaches the next step to the future, and it does not wait. Python's
add_done_callback(fn)attaches the callablefnto the future, andfnis called when the future is cancelled or finishes running.3 See the callback pattern and async/await. - Promise pipelining. The caller sends calls to a future before its value is known. The use of futures can dramatically reduce latency in distributed systems, for example with promise pipelining, as implemented in the languages E and Joule.1
An active object returns a future for each request that it puts on its queue. An asynchronous completion token is the other way to match a result to its request: the caller passes a token, and the completion event brings it back.
Known uses
- Java
java.util.concurrent.Future, which an executor'ssubmitreturns.2 - Python
concurrent.futures.Future, whichExecutor.submit()creates.3 - C++
std::future, whichstd::async()returns, with thewait()andget()member functions.1 - Promise pipelining in E and Joule, which the language Argus called call-stream.1
References
- Futures and promises, Wikipedia, lead; Implicit vs. explicit; Promise pipelining; Blocking vs non-blocking semantics
- Java SE 21 API, java.util.concurrent.Future, the interface description; cancel
- concurrent.futures, Launching parallel tasks, Python documentation, Future Objects; ThreadPoolExecutor
- Henry G. Baker, Jr. and Carl Hewitt, The Incremental Garbage Collection of Processes (1977), abstract
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2GNXEZ Edit this page History Report an error Markdown