0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Asynchronous I/O
Futures Promises and Fork Join
A future is a placeholder for a result that is not ready yet. It lets a caller start work, continue with other things, and collect the result later, without managing threads or condition variables directly. This section explains what futures and promises are, how they differ, how callers wait for them, and why they became the standard interface between callers and executors.
A value that arrives later
When a caller submits a task to an executor, it needs some way to get the result back. Without a shared abstraction, every task would need its own condition variable and result field, and every caller would need to write the waiting logic correctly. A future packages this: it is an object returned immediately when work is started, which will eventually hold either a value or an error. The caller can check whether it is done, wait for it, wait with a timeout, or attach code to run when it completes. Java has Future and CompletableFuture, C++ has std::future, Python has concurrent.futures.Future and asyncio.Future, JavaScript has Promise, Rust has the Future trait, and C sharp has Task. The names and details differ, but the idea is the same everywhere: separate starting a computation from consuming its result.
Futures also make concurrency explicit at the call site. A function that returns a value forces the caller to wait for it, while a function that returns a future lets the caller decide. Starting three independent requests and then waiting for all three takes the time of the slowest rather than the sum, and the code that does this reads almost like sequential code: start a, start b, start c, then wait for each.
Promise and future as two ends
Many libraries split the abstraction into two halves. The future is the read side, held by the consumer, which can only wait for and read the result. The promise is the write side, held by the producer, which can only complete it with a value or an error, exactly once. In C++, std::promise and std::future are separate objects connected by a shared state. In Java, CompletableFuture combines both: anyone holding it can call complete. In JavaScript, a Promise is the read side, and the resolve and reject functions passed to its constructor are the write side. Separating the two makes ownership clear: the code that holds the promise is responsible for completing it, and if it forgets, for example by throwing before reaching the complete call, every consumer waits forever. Good libraries detect this when possible; a C++ promise destroyed without being satisfied stores a broken promise error, so the waiting future throws instead of hanging.
Waiting for a result
The simplest way to consume a future is to block on it with get. This is easy to understand but has the usual costs of blocking: the waiting thread is occupied doing nothing, and waiting without a timeout risks hanging forever if the producer never completes. Production code should almost always wait with a timeout, and decide what to do if it expires: return an error, use a fallback value, or cancel the work. Blocking get inside a task that itself runs on a bounded executor is particularly dangerous, because if the task it waits for is queued behind it on the same executor, neither can make progress. This pool induced deadlock is one of the most common bugs in code that uses futures, and it is the main reason modern APIs encourage composing futures with callbacks rather than blocking on them.
Errors travel with the result
A future holds either a value or an error, and the error is delivered to whoever consumes the result. When a task throws, the executor catches the exception and stores it in the future; calling get later rethrows it, often wrapped, as Java does with ExecutionException. This is a significant improvement over raw threads, where an exception in a thread is printed and lost. It also creates a new failure mode: if nobody ever consumes a failed future, the error is silently lost. JavaScript reports unhandled promise rejections for this reason, and Python asyncio logs a warning when a task with an exception is garbage collected without its result being retrieved. Every future that is created should have a consumer that observes its outcome, even when the value itself is not needed.
Eager and lazy futures
Languages disagree about when the work behind a future starts. In Java, JavaScript and C sharp, futures are eager: calling a function that returns a CompletableFuture, a Promise or a Task has already started the work, and the future is just a handle to something in progress. In Rust, futures are lazy: creating a future does nothing until it is polled, usually by awaiting it or handing it to an executor with spawn, so forgetting to await a future means the work never happens at all. Python coroutines are lazy in the same way, while asyncio tasks created with create_task are eager. The difference changes how code must be written. With eager futures, starting several operations and then awaiting each gives parallelism automatically. With lazy futures, awaiting them one after another runs them sequentially, and parallelism requires an explicit join or spawn. Engineers moving between languages often get this wrong in one direction or the other.
Shared state and futures
A future passes one value from producer to consumer safely: completing the future happens before any read of its result, so the consumer sees everything the producer wrote before completing it. This visibility guarantee is part of every serious futures library, and it means that data passed through a future needs no extra synchronization. It does not, however, protect other shared state. Tasks that run in parallel and update a shared map, counter or list still race, exactly as raw threads do. The cleanest designs avoid shared mutable state entirely: each task computes a result from its own inputs and returns it through its future, and the caller combines the results after they complete. This style, sometimes called pure task parallelism, is easier to reason about and to test, and it scales without locks.
Already completed futures
Libraries offer ways to create futures that are already complete, such as CompletableFuture.completedFuture, Promise.resolve and Task.FromResult. They are useful when a function must return a future but already has the answer, for example from a cache, and they let callers treat cached and uncached results uniformly. They also make tests simple, since a stub can return a completed future without starting any real work. Their failed counterparts, failedFuture and Promise.reject, let a function report a validation error through the same channel as asynchronous errors, so callers have one place to handle failures rather than both a thrown exception and a failed future.
Most of the rest of this course builds on this idea, since async functions, task groups and structured concurrency all return or manage futures underneath, so the habits formed here carry directly into the asynchronous lessons that follow.
A future is a handle to a result that will arrive later, holding either a value or an error. Start independent work early and wait late to overlap it. Always wait with a timeout, never block inside a task on a future scheduled on the same bounded pool, and make sure every failed future is observed by someone.