Chapter 3. State and Concurrency

Let’s think about state.

So far we have handled things in a purely functional style. Vars, like when we were using def and defn, were global and immutable. And bindings in a let form stayed in the let form. This functional style is beautiful and lets us write cleaner and more understandable code, but we still need to deal with the real world. And the real world has state. Luckily, Clojure has a solution for us.

Handling Real-World State and Concurrency

State is messy. In most object-oriented langauges, state gets so tangled up in the code that it becomes really hard to understand what is going on. If you then have to take all that complexity and try to do concurrent programming on it, it quickly becomes a disaster. Clojure has a way around this. Its concurrency flows naturally from its key combination of functional style and immmutable data structures. Let’s dive in and start exploring it with the humble Clojure atom.

Using Atoms for Independent Items

Atoms are designed to store the state of something that is independent, meaning we can change the value of it independently of changing any other state.

Alice is currently exploring Wonderland and just met a curious caterpillar that is sitting upon a mushroom. It isn’t a giant caterpillar. Rather, it is Alice that is still small.

Let’s create an atom called who-atom with the initial value of :caterpillar. We can create one using a def form and the atom form. The atom form creates a new atom and ...

Get Living Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.