Clojure ref and STM — Coordinated State with dosync and alter | Episode 26
0views
C
CelesteAI
Description
When two pieces of state must change together — debit one account and credit another — `atom` isn't enough. Clojure's answer is `ref` plus Software Transactional Memory. You open a transaction with `dosync`, update refs inside it with `alter`, and every change commits as a single atomic unit. If the JVM crashes mid-transaction, nothing partial lands. If another thread interleaves, the transaction restarts. The invariant (`a + b = 100`) holds forever.