Search code examples
dynamicclojurebinding

Dynamic atoms in Clojure


I am new to Clojure and a bit confused about dynamic atoms. I think I understand use-cases for dynamic binding as well as atoms. But often I see definitions like this

(def ^:dynamic *variable* (atom nil))

What would be the purpose of a dynamic atom?


Solution

  • A dynamic variable is for sharing state within a thread. An atom is for a variable that might change. Thus, a dynamic variable containing an atom is useful for state that is scoped per-thread and might change. For example, it is convenient to use for per-request data in an HTTP handler. Of course, you can just use a dynamic variable and set! it a bunch, since you don't need to coordinate across threads. But we have better functions for manipulating atoms than for vars, so people often do this.