Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท State and Concurrency

Identity, State and Atoms

Understand Clojure's model of identity and state, then use atoms for synchronous, uncoordinated updates: deref, swap!, reset!, compare-and-set!, watches and validators.

Clojure's data is immutable, yet real programs change over time: a counter increments, a cache fills, a user logs in. Clojure's answer is to separate three ideas:

  • A value is an immutable fact, such as {:count 5}.
  • An identity is a stable thing you refer to, such as "the page counter".
  • State is the value an identity has at a particular moment.

A mutable object in most languages mixes all three: the same object is the identity and its contents change in place. Clojure keeps values immutable and gives you reference types that point at one value at a time and move to a new value in a controlled, thread-safe way. The simplest reference type is the atom.

Creating and reading atoms

CLOJURE
(def counter (atom 0))

@counter           ;=> 0       ; shorthand for (deref counter)
(deref counter)    ;=> 0

@ (or deref) takes a snapshot of the current value. The snapshot is a normal immutable value; later changes to the atom do not alter it.

Changing atoms: swap! and reset!

CLOJURE
(swap! counter inc)       ;=> 1
(swap! counter + 10)      ;=> 11    ; (+ current 10)
(reset! counter 0)        ;=> 0     ; replace regardless of the old value

swap! takes a function, applies it to the current value (plus any extra arguments), and stores the result. It returns the new value. Prefer swap! to reset! whenever the new value depends on the old one, because swap! is atomic.

How swap! stays safe

Atoms use compare-and-set with automatic retry. swap! reads the current value, computes (f current), and tries to install the result only if the atom still holds the value it read. If another thread changed the atom in the meantime, swap! discards its attempt and runs f again against the new value.

sequenceDiagram
  participant T as Thread
  participant A as Atom
  T->>A: read value v1
  T->>T: compute (f v1)
  T->>A: compare-and-set v1 to v2
  alt atom still holds v1
    A-->>T: success, v2 stored
  else changed by another thread
    A-->>T: fail, retry with the new value
  end

Because swap! may retry, the function you pass must be pure and free of side effects. Never send an email or increment an external counter inside swap!.

Holding richer state

Atoms usually hold a map, and you update it with the functions you met in the data structure chapters: assoc, update, assoc-in, dissoc.

CLOJURE
(def session (atom {:user nil :cart []}))

(swap! session assoc :user "ana")
(swap! session update :cart conj {:sku "pen" :qty 2})
(swap! session update-in [:cart 0 :qty] inc)

@session
;=> {:user "ana", :cart [{:sku "pen", :qty 3}]}

One atom holding one map is easier to reason about than many separate atoms, because a single swap! updates every part of the state atomically.

compare-and-set! and swap-vals!

(compare-and-set! a old new) sets the atom only if it currently equals old (by identity) and returns true or false. It is the low-level primitive behind swap! and is rarely needed directly.

swap-vals! and reset-vals! return both the old and the new value as a pair, which is handy when you must know what was replaced:

CLOJURE
(def a (atom 5))
(swap-vals! a inc)    ;=> [5 6]
(reset-vals! a 100)   ;=> [6 100]

Watches and validators

A watch is a function called after the atom changes:

CLOJURE
(add-watch counter :logger
  (fn [key ref old-val new-val]
    (println "counter changed from" old-val "to" new-val)))

(swap! counter inc)
; prints: counter changed from 0 to 1
(remove-watch counter :logger)

The key lets you add several watches and remove them individually. Watches run on the thread that did the change, so keep them quick.

A validator is a function that must return truthy for a proposed new value; if it does not, the change is rejected with an exception and the atom keeps its old value.

CLOJURE
(def stock (atom 10 :validator #(>= % 0)))

(swap! stock - 3)    ;=> 7
(swap! stock - 100)  ; throws IllegalStateException: Invalid reference state
@stock               ;=> 7

Validators are an excellent way to enforce invariants such as "stock never goes negative" in one place.

When to use an atom

Atoms suit independent state: caches, counters, configuration, an in-memory store, the current game state. Updates are synchronous (the call returns when done) and uncoordinated (an atom does not take part in a transaction with other references). If two pieces of state must change together or not at all, see refs and STM. If you want asynchronous updates, see agents.

Don't reach for def plus a mutable Java object just to hold state; an atom is almost always the right default.

Try it: an atom in JavaScript

JavaScript is single-threaded here, so this stand-in demonstrates the API shape: deref, swap with a pure function, a watch and a validator.

JS A tiny atom

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: immutable values, changing identity

This example shows why the model works: each state is a new, frozen value, and old snapshots stay valid.

JS Snapshots stay unchanged

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must the function passed to swap! be free of side effects?

    swap! uses compare-and-set and retries on conflict, so the function can run more than once.
  2. 2. What does (swap! counter + 10) compute?

    swap! calls the function with the current value as the first argument followed by the extra arguments.
  3. 3. What happens when a validator returns false for a proposed value?

    The change is rejected with an IllegalStateException and the atom keeps its previous value.
  4. 4. When should you prefer a ref over an atom?

    Atoms are independent. Coordinated changes across multiple references need refs and dosync.

Summary

  • Clojure separates immutable values from identities that point to successive values over time.
  • An atom is synchronous, uncoordinated state: read with @, change with swap! (pure function, may retry) or reset!.
  • swap-vals! returns old and new values; compare-and-set! is the underlying primitive.
  • Watches react to changes; validators enforce invariants.
  • One atom holding one map keeps related state consistent.

Next: Refs and Software Transactional Memory