14 Concurrency

 

Unlike other mainstream languages, Clojure main approach to concurrency does not require explicit locking [219]. Locking is still available as a low level option, but the default use of persistent data structures provides Clojure with alternative strategies to solve the hardest concurrency problems.

This chapter describes what functions in the standard library are dedicated to concurrency and how to use them. There are three main groups of them:

  • future, promise and delay control threads in different ways. These functions are not connected to a specific way to handle state, nor they wrap any state themselves.
  • ref, atom and agent are concurrency model designed to handle state, each one providing different guarantees in case of concurrent access. var and volatile! also belong to this group, but they are illustrated in other chapters for their role in scenarios other than pure concurrency.
  • deref, validators and watchers are common features implemented in all concurrency models.
  • Finally, locking is the last resort in terms of concurrency handling around critical sections of the code. The need for explicit locking is normally exceptional and relegated to some case of low level Java interoperability.

14.1 future

[Note]  Note

This section also mentions other related functions such as: future-call, future-done?, future-cancel, future-cancelled? and future?

future takes one or more expressions as input and evaluates them asynchronously in another thread:

14.2 promise and deliver

14.3 delay

14.4 ref

14.5 atom

14.6 agent

14.7 deref and realized?

14.8 set-validator! and get-validator