Skip to content

clojure.core/commute

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 2 Runnable: 0
([ref fun & args])

Must be called in a transaction. Sets the in-transaction-value of ref to:

(apply fun in-transaction-value-of-ref args)

and returns the in-transaction-value of ref.

At the commit point of the transaction, sets the value of ref to be:

(apply fun most-recently-committed-value-of-ref args)

Thus fun should be commutative, or, failing that, you must accept last-one-in-wins behavior. commute allows for more concurrency than ref-set.

Examples

by leifp on . May have evaluation errors.
by cloojure on . May have evaluation errors.

Note by dedeibel

Note to understand the difference to 'alter':

Commute should be used when it doesn't matter whether anyone else has changed (altered or commuted) the ref using a successful transaction. This often implies that this ref is not affected by any conditions, i.e. it should be changed the same way no matter what. (thanks to raek for clarifying that for me)

Note by m0wfo

In the concurrency video RH explains that commute is useful for actions where the order in which they alter the value doesn't matter, e.g. incrementing a counter.

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.