concept commute in category clojure

appears as: commute
The Joy of Clojure, Second Edition

This is an excerpt from Manning's book The Joy of Clojure, Second Edition.

In this section, we’ll discuss some refactorings that are possible for the chess board example. You’ll first fix some nagging problems with the example. Next, we’ll discuss how you can take advantage of commutativity (action order independence) in the design using Clojure’s commute function. Finally, we’ll talk about how to adjust a ref’s default settings to avoid excessive retries.

The function ref-set is different from alter and commute in that instead of changing a ref based on a function of its value, it does so given a raw value:

(dosync (ref-set to-move '[[:K [2 1]] [:k [0 1]]]))

;=> [[:K [2 1]] [:k [0 1]]]

In general, this sort of vulgar change should be avoided. But because the refs have become out of sync during your experiments with commute, you can be forgiven in using ref-set to fix it—just this once.

10.2.2. Commutative change with commute

Figure 10.8 showed that using alter can cause a transaction to retry if a ref it depends on is modified and committed while it’s running. But there may be circumstances where the value of a ref in a given transaction isn’t important to its completion semantics. For example, the num-moves ref is a simple counter, and surely its value at any given time is irrelevant for determining how it should be incremented. To handle these loose dependency circumstances, Clojure offers an operation named commute that takes a function to apply to a ref. Of particular note is that the function you give to commute is run at least twice during the course of a transaction to help increase the level of concurrency around the given reference. Increasing the concurrency in a system is good, right? Well, maybe. What if you were to change the move-piece function to use the commute function instead of alter?

Thanks to your rash decision, you’ve once again introduced inconsistency into the system. But why? The reason lies in the fact that the new update-to-move isn’t amenable to the semantics of the commute function. commute allows for more concurrency in the STM by devaluing in-transaction value disparity resulting from another transaction’s commit. In other words, figure 10.9 shows that the in-transaction value of a ref is initially set as when using alter, but the commit time value is reset just before commute commits.

Figure 10.9. The in-transaction value 9 in the nummoves ref is retrieved in the body of the transaction and manipulated with the commute function. But the commute function inc is again run at commit time with the current value 13 contained in the ref. The result of this action serves as the committed value 14.