4 ms·
Aren't atoms a part of STM in clojure?
by DigitalJack 11y ago
Aren't atoms a part of STM in clojure?
- hawkice 11y agoNah, you can't update two atoms and make sure they both change at the same time. That being said, 99% of the time you can have one atom, a map, with two keys, and that'll do it.
- eveningcoffee 11y agoNope, atoms are based on simple CAS (Compare And Swap) operation that replaces the reference value. They are pretty much a sugar around AtomicReference in Java (in case of JVM implementation of course). It is pretty much as like this 1. Dereference a variable and keep the old reference. 2. Create a new modified variable. 3. Use CAS on old reference and new variable to update the reference to point to the new vairable. In case of failure (some other thread made the update before) go to 1. But the version of SMT implemented in Closure is very similar to the CAS, just now you can apply it to the multiple variables i.e. it is multi variable CAS. It has the same drawbacks and advantages as atomic references: your code does not depend on lock taking order (as they are managed by the transaction manager) and you avoid dead locks as the locks are taken in the same order before applying the update, but now two different threads can start the transaction to update the same variable, but only one of them can finish as the first one and the other one should be cancelled and repeated. In principle you can get away with a simple atomic reference (that is much faster) when the set of the updated variables is always the same - you make a pair of them and update them together.
- DigitalJack 11y agoInteresting. I've never needed anything other than the occasional atom.