← Lessons

quiz vs the machine

Gold1430

Concurrency

Agents and Refs Clojure Style

Identities that change over time without shared mutation.

5 min read · core · beat Gold to climb

Separating identity from value

In a functional concurrency model, a value is an immutable snapshot, while an identity is a stable reference that points at a succession of values over time. You never mutate a value; you make the identity point at a new one.

Refs for coordinated change

A ref is an identity meant to change together with others inside a transaction. When two accounts must transfer money, both refs update in one atomic STM transaction, so no observer ever sees money missing or doubled.

Agents for independent change

An agent is an identity for asynchronous updates. You send it a function; the runtime applies that function to the agent current value later, on its own thread, one action at a time. Sends from many threads are queued, so the agent state is never raced.

When to use which

  • Use refs when several identities must change together atomically.
  • Use agents when one identity changes independently and you do not need the result immediately.

Both keep values immutable; only the pointer moves.

Key idea

Refs and agents are identities over immutable values, changed by coordinated transactions or by serialized asynchronous functions.

Check yourself

Answer to earn rating on the learn ladder.

1. What distinguishes an identity from a value in this model?

2. When should you choose a ref over an agent?