Atoms
I recently found myself using atoms for the first time in my clojure code, and figured I’d share the basics.
What is an atom?
An atom in Clojure is a reference type that allows you to manage shared, synchronous, and independent state. It provides a way to store a single value that can be changed atomically, meaning that changes to the value are guaranteed to be visible to all threads in a consistent way.
Atoms are useful when you have a value that needs to change over time, and these changes need to be coordinated across different parts of your application.
Creating and using an atom
You can create an atom using the atom function:
(def counter (atom 0))
Here, counter is an atom holding the value 0. You can access the value of an atom using the @ reader macro or the deref function:
(println @counter) ; prints 0
Updating Atoms
To change the value of an atom, you use the swap! or reset! functions.
- swap!: This function updates the value of an atom by applying a function to the current value. It’s useful when
the new value depends on the old one.
(swap! counter inc) (println @counter) ; prints 1
- reset!: This function replaces the current value of the atom with a new value, regardless of the current state.
(reset! counter 10) (println @counter) ; prints 10