Day 2: Agents and Software Transactional Memory

Yesterday we looked at atoms. Today we’ll look at the other types of mutable variables provided by Clojure: agents and refs. Like atoms, agents and refs are both concurrency aware and work in concert with persistent data structures to maintain the separation of identity and state. When talking about refs, we’ll see how Clojure supports software transactional memory, allowing variables to be modified concurrently without locks and yet still retaining consistency.

Agents

An agent is similar to an atom in that it encapsulates a reference to a single value, which can be retrieved with deref or @:

​ 
user=>​ (def my-agent (agent 0))​
​ 
#'user/my-agent
​ 
user=>​ @my-agent​
​ 
0

Get Seven Concurrency Models in Seven Weeks 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.