A root binding is the optional value associated with a Clojure var. Unlike a dynamic binding, which belongs to one thread, a root binding is visible from all threads and represents the most typical use of a var. section 16.0
Root bindings have several practical behaviors:
- A var is bound when it has a root value; it is thread-bound when at least one thread-specific value exists. section 16.0
- alter-var-root replaces the root value by applying a function to the old value, and performs that change atomically. section 16.3
- with-redefs and with-redefs-fn temporarily replace root bindings, restoring the previous bindings when the enclosing form exits. section 16.3
- Inlining can take precedence over the root binding, so changing a var with alter-var-root may have no visible effect until inline metadata is removed. section 16.3
Updating a root value
(def a-var {:a 1}) (alter-var-root #'a-var update-in [:a] inc) ;; {:a 2} alter-var-root receives the old root value and installs the function's result. section 16.3
Testing versus thread-local rebinding
with-redefs can replace a root binding while testing code such as fetch-title, but concurrent use is unsafe. Dynamic vars with binding provide separate values for concurrent futures instead.
