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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access