liveBook · Manning

Root binding

As explained in Clojure: The Essential Reference

A root binding is the optional value associated with a Clojure var that is visible from all threads.

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.

How Clojure: The Essential Reference covers it

How deep it goes
Explains definition, binding states, atomic updates, temporary overrides, concurrency hazards, and inlining precedence.
Examples
Demonstrates map updating, delayed atomic replacement, inlining interference, test stubbing, and unsafe concurrent redefinition.
What it assumes
Assumes familiarity with Clojure vars and namespaces, while distinguishing root, dynamic, and thread bindings explicitly.
What you can do after
Apply it via alter-var-root or temporary redefinition, while choosing dynamic binding for thread-specific concurrent values.
How it connects
Connects vars with namespaces, dynamic binding, thread binding, metadata, inlining, alter-var-root, and with-redefs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.