O'Reilly logo

Clojure High Performance Programming - Second Edition by Shantanu Kumar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transients

Earlier in this chapter, we discussed the virtues of immutability and the pitfalls of mutability. However, even though mutability is fundamentally unsafe, it also has very good single-threaded performance. Now, what if there was a way to restrict the mutable operation in a local context in order to provide safety guarantees? That would be equivalent to combining the performance advantage and local safety guarantees. That is exactly the abstraction called transients, which is provided by Clojure.

Firstly, let's verify that it is safe (up to Clojure 1.6 only):

user=> (let [t (transient [:a])] @(future (conj! t :b))) IllegalAccessError Transient used by non-owner thread clojure.lang.PersistentVector$TransientVector.ensureEditable (PersistentVector.java:463) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required