Question

How do atoms and refs actual differ?

I understand that atoms are declared differently and are updated via the swap! function, whereas refs use alter inside a dosync. The internal implementation, however, seems quite similar, which makes me wonder why I would use one and not the other.

For example, the doc page for atoms (http://clojure.org/atoms) states:

Internally, swap! reads the current value, applies the function to it, and attempts to compare-and-set it in. Since another thread may have changed the value in the intervening time, it may have to retry, and does so in a spin loop. The net effect is that the value will always be the result of the application of the supplied function to a current value, atomically. However, because the function might be called multiple times, it must be free of side effects.

The method described sounds quite similar to me to the STM used for refs.

Was it helpful?

Solution

The difference is that you can't coordinate changes between multiple atoms but you can coordinate changes between multiple refs.

Ref changes have to take place inside of a dosync block. All of the changes in the dosync take place or none of them do (atomic) but that extends to all changes to the refs within that dosync. This behaves a lot like a database transaction.

Let's say for example that you wanted to remove an item from one collection and add it to another but without anyone seeing a case where neither collection has the item. That's impossible to guarantee with atoms but you can guarantee it with refs.

OTHER TIPS

Keep in mind that:

  • Use Refs for synchronous, coordinated and shared changes.
  • Use Atoms for synchronous, independent and shared changes.

To me, I don't care about the implementation differences between the atoms and refs. What I care about is the "Use Cases" of each on of them.

I use refs with I need to change the state of more than one reference type and I need the ATM semantics. I use atoms when I change the state of one reference type (object, depends on how you see it).

For example, if I need to increase the number of page hits in a web analytics system; I use atoms. If I need to transfer money between two accounts, I use refs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top