Dynamic var binding and state

The fourth kind among the Clojure's reference types is the dynamic var. Since Clojure 1.3, all the vars are static by default. A var must be explicitly declared so in order to be dynamic. Once declared, a dynamic var can be bound to new values on per-thread basis. Binding on different threads do not block each other. An example is shown here:

(def ^:dynamic *foo* "bar")
(println *foo*)  ; prints bar
(binding [*foo* "baz"] (println *foo*))  ; prints baz
(binding [*foo* "bar"] (set! *foo* "quux") (println *foo*))  ; prints quux

As the dynamic binding is thread-local, it may be tricky to use in multi-threaded scenarios. Dynamic vars have been long abused by libraries and applications as a means to pass in a common argument ...

Get Clojure High Performance Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.