Futures
With pmap
, Clojure takes care of all the thread management for you, which makes things easy. A lot of times, however, you need more control over your threads than what pmap
provides. Clojure's futures do just this. They are a mechanism for spawning and waiting for new threads.
Consider a situation where two expensive calculations are needed to perform a third operation, such as adding the two results together. In a single-threaded context, we would just write this:
(+ (expensive-calc-1 5) (expensive-calc-2 19))
Written this way, the call to expensive-calc-1
needs to complete before expensive-calc-2
can start. If the calculations could be run in parallel, we would cut the execution time nearly in half, in the best cases. Running the two threads in parallel creates some new problems, though. We need a way of coordinating the return values, especially since we don't know whether expensive-calc-1
or expensive-calc-2
will complete first. We need a way to wait...