O'Reilly logo

Clojure High Performance Programming 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

Dynamic var binding and state

The fourth kind of Clojure reference type is the dynamic var. Since Clojure 1.3, all vars are static by default. A var must be explicitly declared in order to be dynamic. Once declared, a dynamic var can be bound to new values on a per-thread basis.

Bindings on different threads do not block each other. An example is as follows:

(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 dynamic binding is thread-local, it may be tricky to use in multithreaded scenarios. Dynamic vars have been long abused by libraries and applications as a means to pass in a common argument to be used by several ...

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