With Clojure (and other Lisp dialects) you can modify running code. So, when a function is modified during runtime is that change made available to multiple threads?
I'm trying to figure out how it works technically in a concurrent setting: if several threads are using a function foo, what happens when I redefine (say using defn) the function foo?
There has to be some synchronization going on: when and how does such synchronization happen and what does it cost?
Say on a JVM, is the function referenced using a volatile
reference? If so, does it mean every single time there's a "function lookup" then one has to pay the volatile
cost?
In Clojure functions are instances of the IFn
class and they are almost always stored in vars
. vars are Clojures mechanism for thread local values.
binding
which gives then their own thread local value that they are free to change at will because no other thread can read it. A good understanding of vars is well worth a little study, they are a very useful concurrency device once you get used to them.
ps: the root thread is usually the REPL pss: you are of course free to store your functions in something other than vars, if for instance you needed to atomically update a group of functions, though this is rare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With