Managing Per-Thread State with Vars

When you call def or defn, you create a dynamic var, often called just a var. In all the examples so far in the book, you pass an initial value to def, which becomes the root binding for the var. For example, the following code creates a root binding for foo of 10:

 ​(​def​ ^:dynamic foo 10)​
 ​-> #'user/foo​

The binding of foo is shared by all threads. You can check the value of foo on your own thread:

 ​foo​
 ​-> 10​

You can also verify the value of foo from another thread. Create a new thread, passing it a function that prints foo. Don’t forget to start the thread:

 ​​user=>​ (.start (Thread. (​fn​ [] (println foo))))​
 ​-> nil​
 ​| 10​

In the previous example, the call to start returns nil, and then the ...

Get Programming Clojure, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.