Ref-set vs commute vs alter

What is the difference in 3 ways to set ref value in Clojure? I read documents about ref-set, commute and alter several times. I am rather confused about which ones to use at what time. Can someone give me a brief description of what the differences are and why each is needed?

+48
clojure
Feb 15 '11 at 2:05
source share
1 answer

As a simple explanation of how software transactional memory system works in clojure; it repeats transactions until all of them pass without changing the values ​​from under it. You can help him make this decision using the ref-change-functions functions that give him hints about which interactions are safe between transactions.

  • ref-set used when you do not need the current value. Just set it on ! ref-set saves you from writing something like (alter my-ref (fun [_] 4)) to set my-ref to 4. (ref-set my-ref 4) sure that looks a lot better: )
    Use ref-set to just set the value.

  • alter is the most common standard. Use this function to change the value. This is STM meat. It uses the function you passed to change the value and tries again if it cannot guarantee that the value has not changed since the start of the transaction. It is very safe, even in some cases when you do not need it to be safe, for example, by increasing the counter. You probably want to use alter most of the time.

  • commute is an optimized version of alter for those times when the order of things really doesn't matter. it doesn't matter who added that +1 to the counter. The result is the same. If the STM decides whether the transaction is safe to complete the transaction, and it has only conflicts during dial-up operations and none of them can be changed, then it can go forward and commit new values ​​without the need to restart any user. This can save an accidental transaction attempt, although you will not see the huge benefits of this in regular code.
    Use commute when you can.

+77
Feb 15 '11 at 4:32
source share



All Articles