Thanks for the discussion This is not a reply to any particular post. Here is my thinking on the various points raised.
1. The length of the critical section is irrelevant in this discussion. Even with locks, people agree that the critical section should be as short as possible. So the limiting factor is the algorithm itself, with or without lock. 2. I assume even with STM style atom, some kind of lock is happening internally, for the final commit, because when committing, you still need to coordinate the access to some state with other threads. Maybe it is not called a lock, but something similar. So that same mechanism can be used to lock the whole swap! and should not increase any overhead. 3. Is lock so expensive? Let's find out. tbc++ showed my implementation is much slower. That's true, because I want to have a separate type so there is no chance to mix swap! and lock-swap! on one object. And that "apply" is slow too. Let's have a more fair comparison by changing the original lock-swap! to this: (defn lock-swap! [lock-atom f x] (locking lock-atom (swap! lock-atom f x))) user> (time (dotimes [x 1000000] (swap! a (fn [o n] n) x))) "Elapsed time: 41.417993 msecs" nil user> (time (dotimes [x 1000000] (lock-swap! a (fn [o n] n) x))) "Elapsed time: 136.342714 msecs" nil The difference is 3.3 times. But consider swap! is already doing some kind of internal locking at commit time as I mentioned before, I am doing (unnecessary) double-locking here, so the actual difference is less (maybe by half, if we assume fn [o n] is super fast). There might be more optimization room If we move the lock into the Clojure core. But the point is, lock is not that expensive at all here. 4. Some may argue that the STM style atom swap is not always better than lock style swap, but sometimes it is (the claim that it is not optimized for all use cases). Given lock is not expensive, can anyone give an example in what case STM style atom swap is better than lock based swap? Basically I am thinking STM atom is always no-better than lock based atom. Even for real-time system, the fact that you don't know when (and how many) re-try may happen will reduce its usefulness a lot. -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en