Use Atoms for Uncoordinated, Synchronous Updates

Atoms are a lighter-weight mechanism than refs. Where multiple ref updates can be coordinated in a transaction, atoms allow updates of a single value, uncoordinated with anything else.

You create atoms with atom, which has a signature similar to ref:

 (atom initial-state options?)
 ; options include:
 ; :validator validate-fn
 ; :meta metadata-map

Returning to our music player example, you could store the current-track in an atom instead of a ref:

 (​def​ current-track (atom ​"Venus, the Bringer of Peace"​))
 -> #​'user/current-track

You can dereference an atom to get its value, just as you would a ref:

 (deref current-track)
 -> ​"Venus, the Bringer of Peace"
 @current-track
 

Get Programming Clojure, 3rd Edition 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.