megaref
STM ref types that allow for more concurrency on associative values.
megaref: bigger STM values without restructuring
Two new Clojure STM reference types, associative refs and subrefs, let concurrent transactions update different keys of one value at once instead of fighting over the whole ref.
What the two refs do
An associative ref, the megaref itself, is built for concurrent path-keyed updates. Because two transactions can touch different keys without colliding, a megaref can hold larger values than an ordinary ref and still keep contention low. A subref then offers a scoped view over one associative ref, and its main job is to stand in for plain refs so an existing codebase can move onto megarefs without reshaping the code.
Path level operations
Alongside the ref types come alter-in, commute-in, deref-in, ref-set-in, and ensure-in, each carrying the same STM semantics as its whole-ref counterpart but applied at a path. Two alter-in calls on different paths of the same ref, say [:a :b :c] and [:a :b :d], do not conflict, while [:a :b] and [:a :b :c] do. The prefix check behind that can be switched off with the :check-prefixes option, and the author warns to do so only when paths are never prefixes of one another.
How the concurrency dials work
The :guards-count option sets the number of stripes a megaref uses, and higher values raise throughput until it plateaus. Picking a number depends on how concurrent the app is, the average number of paths a transaction modifies, average path length, and the :check-prefixes setting. At runtime the options, including the validator function and history settings, can be read and changed through one uniform interface, get-options and set-option!.
Migrating a codebase
The suggested migration is to aggregate several refs into one megaref, replace those refs with subrefs on it, and swap every alter, commute, ref-set, and ensure call for its drop-in replacement, which works on both plain refs and the new types. The repo links a pair of commits showing the original STM ants demo by Rich Hickey converted this way, which is about as concrete a before-and-after as a migration note can get.
Editorial conclusion
The library keeps Clojure's STM semantics while moving locking granularity from whole refs to individual paths, which is the whole payoff for most users.
Community notes