Futures, Delays, and Promises

Learn about the functionalities in Clojure that allow concurrency and parallelism.

Overview

Clojure has handy functions that help us deal with concurrent and parallel programming. Futures, delays, and promises are some of these tools. They do this by giving us flexibility in our serial code.

Clojure has three steps that occur when we talk about a task:

  1. Task definition

  2. Task execution

  3. Task result

These steps normally happen at runtime. They ensure that for most of the functions created in Clojure, as soon as they encounter a task definition, they execute it. Furthermore, it also requires the result at the same time, blocking the process until it’s finished.

Part of learning concurrent programming is learning to identify when these chronological couplings aren’t necessary. Futures, delays, and promises allow us to separate task definition, task execution, and requiring the result.

Futures

In Clojure, the future macro can be used to define a task and place it on another thread without requiring the result immediately. It will evaluate the expression put in the future in a separate thread, which we don’t have to set up.

The declaration of this function is (future & body), in which the body can be a sequence of expressions that will be on hold and will be invoked in another thread. It will cache the result and return it on all subsequent calls to deref or @.

In the following code widgets, “Execution Timed Out!” appears in the output. This is due to a limitation in our widget, so don’t worry about it.

Get hands-on with 1400+ tech skills courses.