man clojure/transients
Transients: how Clojure mutates in private
Clojure’s maps are immutable, and every assoc returns a new one. So how
does frequencies count a million items without building a million maps?
(frequencies [:a :b :a :c :a]) ;=> {:a 3, :b 1, :c 1}
The answer is a transient: a temporary, mutable version of the map that
only the function building it can see. This article reads how transients work
in Clojure 1.12.7, in core.clj and the map classes, and checks it with
scripts run with clojure -M on OpenJDK 27.0.1.1 on an Apple M2 Pro. Every
claim below comes from that source, Clojure’s changelog, or one of those
scripts.
The short version
(transient m) wraps the persistent map’s root in a new object and a new
edit token. Every node the transient creates carries that token. When
the transient changes a node that has its token, it writes into the node’s
array directly. When it meets a node without its token, one shared with the
original map, it copies that node first and keeps the copy. persistent!
clears the token, which freezes every node at once, and wraps the root in an
ordinary persistent map. Both calls are O(1). The original map never
changes.
The API
There are three parts. transient makes the editable version, the
functions ending in ! (assoc!, conj!, dissoc!, disj!, pop!)
change it, and persistent! ends the session. Transients exist for
array maps, hash maps, hash sets and vectors, the four classes that
implement IEditableCollection. (transient (sorted-map)) and
(transient '(1 2)) throw ClassCastException.
frequencies is the whole pattern in six lines
(core.clj L7355-L7364):
(defn frequencies
[coll]
(persistent!
(reduce (fn [counts x]
(assoc! counts x (inc (get counts x 0))))
(transient {}) coll)))
group-by has the same shape with conj on a vector in place of inc
(L7298-L7310),
and into uses conj! on a transient whenever the target collection
supports it
(L7033-L7052).
In each case the transient is created and frozen inside one function, so
the caller only ever sees a persistent map.
The edit token
A PersistentHashMap is a hash array mapped trie: a tree of small nodes,
32-way, keyed by 5 bits of the hash per level. The
companion post on persistent maps covers
the tree. What matters here is that every node class has one extra field,
final AtomicReference<Thread> edit. The persistent assoc of
BitmapIndexedNode and ArrayNode passes null there for every node it
copies.
asTransient makes a TransientHashMap with a new token holding the
current thread
(L295-L306):
TransientHashMap(PersistentHashMap m) {
this(new AtomicReference<Thread>(Thread.currentThread()), m.root, m.count, m.hasNull, m.nullValue);
}
Every transient operation passes that token down the tree. A node decides what to do by comparing tokens by identity (L811-L818):
private BitmapIndexedNode ensureEditable(AtomicReference<Thread> edit){
if(this.edit == edit)
return this;
int n = Integer.bitCount(bitmap);
Object[] newArray = new Object[n >= 0 ? 2*(n+1) : 4]; // make room for next assoc
System.arraycopy(array, 0, newArray, 0, 2*n);
return new BitmapIndexedNode(edit, bitmap, newArray);
}
If the node already belongs to this transient, it is returned as is and the
caller writes into it. Otherwise it is copied, with one spare slot, and the
copy belongs to this transient from then on. ArrayNode does the same with
array.clone()
(L523-L527).
The transient assoc of a bitmap node also inserts a new key in place when
the array has room (n*2 < array.length), and when it has to grow the
array it leaves room for 4 more pairs, 2*(n+4)
(L844-L902).
The persistent version grows by exactly one pair.
So the first assoc! along a path copies that path, like a persistent
assoc. Every later assoc! that reaches the same nodes writes in place.
Watching it happen
The node classes are package-private, but a script runs in the unnamed
module, so reflection can read their fields. I put every node of a
million-key map into an IdentityHashMap, made changes through a
transient, and counted the nodes of the transient’s root that weren’t in
the set before:
(def m (zipmap (range 1000000) (repeat 0)))
(def s0 (node-set (field m "root")))
(def t (transient m))
(def t (assoc! t 5 1))
(def s1 (node-set (field t "root")))
(def t (assoc! t 5 2))
(def s2 (node-set (field t "root")))
(def t (assoc! t 7 1))
(def s3 (node-set (field t "root")))
(println "assoc! 5:" (fresh s0 s1) "new nodes; assoc! 5 again:" (fresh s1 s2)
"; assoc! 7:" (fresh s2 s3))
$ clojure -M trans.clj
assoc! 5: 5 new nodes; assoc! 5 again: 0 ; assoc! 7: 4
edit before persistent!: #object[java.lang.Thread 0x1dbd16a6 Thread[#3,main,5,main]]
edit after persistent!: nil
root's edit is the transient's token: true
second transient, assoc! 5: 5 new nodes
The first assoc! copied the 5 nodes from the root to key 5. The second
one copied nothing. Key 7 shares only the root with key 5, so it copied the
other 4 nodes on its own path. The original m still has 0 at key 5.
What persistent! does
For a hash map, persistent! is two lines
(L354-L357):
IPersistentMap doPersistent() {
edit.set(null);
return new PersistentHashMap(count, root, hasNull, nullValue);
}
It doesn’t walk the tree. The nodes this transient made still point at
the same AtomicReference object, which now holds null. The script’s last
lines show it: the frozen map’s root carries the old token, and the token
is empty.
Clearing it does two things. Every operation on a transient first calls
ensureEditable(), which throws once the token is null
(ATransientMap.java L62-L80):
after persistent!: java.lang.IllegalAccessError: Transient used after persistent! call
And no later transient can edit those nodes, because a new transient gets a
new AtomicReference, and ensureEditable(edit) compares identity. That is
why the second transient in the script had to copy 5 nodes again. The
frozen map stays frozen even if someone makes a transient from it.
The eight-entry trap
The transient docstring warns: “transients are not designed to be bashed
in-place. You must capture and use the return value in the next call”
(L3364-L3377).
This is what happens otherwise.
(let [t (transient {})]
(dotimes [i 10] (assoc! t i i))
(count (persistent! t)))
;=> 8
{} is a PersistentArrayMap, and its transient is a TransientArrayMap
with a fixed array of 16 slots, eight keys and eight values
(PersistentArrayMap.java L486-L495).
The ninth assoc! doesn’t fit, so it builds a transient hash map and
returns that
(L507-L522):
if(len >= array.length)
return PersistentHashMap.create(array).asTransient().assoc(key, val);
Code that ignores the return value keeps using the array map, which still
has eight entries. Checking identical? on each return value shows the
switch.
assoc! returns same object up to 8? [true true true true true true true true false]
Code that works on a small map in testing can lose data on a bigger one.
Threads
The token holds a Thread, which looks like an owner check. It used to be
one. Clojure 1.7’s changelog says: “Prior to Clojure 1.7, transients would
allow modification only from the thread that created the transient. This
check has been removed. It is still a requirement that transients should be
updated by only a single thread at a time.” The reason given (CLJ-1498) is
core.async, where a transient can be created on one thread and used again on
another pooled thread.
In 1.12.7, ensureEditable only tests for null
(L374-L377),
and the thread in the token is never read. An assoc! from a future
works.
assoc! from another thread: {:a 1}
Nothing checks that two threads don’t use one transient at the same time;
that is left to the programmer. In 1.12.7 the transient’s own fields (root, count, hasNull,
nullValue) are volatile, and the same release’s changelog lists
CLJ-1580, “Transient collections should guarantee thread visibility”.
What it saves
I counted a million random ints below 500,000 in one JVM, three ways:
reduce with assoc on {}, the same reduce with assoc! on
(transient {}), and frequencies. Each ran 5 times to warm up, then 10
times timed with System/nanoTime; allocation is
ThreadMXBean.getThreadAllocatedBytes around one more run:
$ clojure -M bench.clj
distinct: 432031
same result: true
persistent assoc 308.7 ms
transient assoc! 153.1 ms
frequencies 147.8 ms
persistent assoc 685.9 MB allocated
transient assoc! 19.5 MB allocated
frequencies 19.5 MB allocated
Over four runs on a busy machine the persistent version took 286 to 312 ms
and the transient one 127 to 158 ms. The allocation numbers were the same
every time. Path copying allocates about 686 bytes per update here, and
the transient 35 times less in total. My own transient reduce and frequencies are the same code, and
they measure the same.
The gap needs volume to show. A whole program that counts 100,000 numbers from stdin spends about 270 ms starting the JVM and Clojure, and at that size I couldn’t measure a difference between the two versions.
Curious facts
persistent!on a transient array map is not free: it copies the used part of its 16-slot array into a new array of exactly that length (L549-L555). On a hash map it allocates one small object.TransientHashMapreuses oneBoxacross all its operations to report whether a key was added. A commented-out line above it allocated a newBoxper call (L301-L333).- Even persistent code uses transients internally.
PersistentHashMap.create, which builds a map from key/value pairs, fills a transient and callspersistent()(L54-L61), and that is what the eight-entry overflow above calls. - A transient read is checked too:
getandcountcallensureEditable(), so reading a transient afterpersistent!also throws (ATransientMap.java L77-L96).
History
- Clojure 1.1:
transient,persistent!,assoc!andconj!(their:addedmetadata). - Clojure 1.2:
frequenciesandgroup-by(:added "1.2"). - Clojure 1.7 (tagged 2015-06-30): the owner-thread check is removed (CLJ-1498), and transients guarantee thread visibility (CLJ-1580).
- Clojure 1.9 (tagged 2017-12-08): CLJ-700, “
contains?,get, andfindbroken for transient collections”. - Clojure 1.10.2 (tagged 2021-01-26):
zipmapuses a transient map (CLJ-1005).
Sources
All Clojure links are at tag clojure-1.12.7.
src/clj/clojure/core.clj: transient and persistent!, assoc!, into, group-by, frequenciessrc/jvm/clojure/lang/PersistentHashMap.java: create, TransientHashMap, ArrayNode.ensureEditable, BitmapIndexedNode.ensureEditable and transient assoc- PersistentArrayMap.java TransientArrayMap
- ATransientMap.java
- changes.md (1.7 “Thread owner check removed on transients”, CLJ-1498, CLJ-1580; 1.9 CLJ-700; 1.10.2 CLJ-1005); tag dates from the GitHub API
- Transient Data Structures, the reference page
grep -rl /lib/clojure/transients/
ls clojure/
- draft Persistent maps in Clojure: HAMTs and structural sharingHow Clojure 1.12.7 makes assoc return a new map without copying the old one: array maps up to eight entries, a 32-way hash array mapped trie after that, Murmur3 hashes, and path copying measured on a million keys.