Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
Yuriy Galanter Avatar asked Mar 03 '23 06:03

Yuriy Galanter


1 Answers

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.

like image 131
amalloy Avatar answered Mar 08 '23 11:03

amalloy