Chapter 6
State and Concurrency

A state is the value of an identity at a point in time.

Quite a lot is packed into the previous sentence. Let’s unpack the word value first. A value is an immutable, persistent data structure. When you can program entirely with values, life is easy, as we saw in Chapter 4, Functional Programming.

The flow of time makes things substantially more difficult. Are the New York Yankees the same now as they were last year? In 1927? The roster of the Yankees is an identity whose value changes over time.

Updating an identity does not destroy old values. In fact, updating an identity has no impact on existing values whatsoever. The Yankees could trade every player, or disband in a fit of boredom, without in any way altering our ability to think about any past Yankees we happen to care about.

Clojure’s reference model clearly separates identities from values. Almost everything in Clojure is a value. For identities, Clojure provides four reference types:

  • Refs manage coordinated, synchronous changes to shared state.
  • Atoms manage uncoordinated, synchronous changes to shared state.
  • Agents manage asynchronous changes to shared state.
  • Vars manage thread-local state.

Each of these APIs is discussed in this chapter. At the end of the chapter, we’ll develop a sample application. The Snake game demonstrates how to divide an application model into immutable and mutable components.

Before we start, let’s review the intersection of state with concurrency and parallelism, as well as look at the difficulty with traditional lock-based approaches.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.255.36