We have now seen how promises, futures, and transactions work in Clojure. We'll now see atoms.
Even though STM is very useful and powerful you'll see that in practice it is not very commonly used.
Atoms are one of Clojure's workhorses, when it comes to concurrent programming.
You can think of atoms as transactions that modify one single value. You might be thinking, what good is that? Imagine you had lots of events that you want to store in a single vector. If you are used to Java, you probably know that using a java.util.ArrayList
package is bound to have problems; since, you are almost surely going to lose data.
In that case, you probably want to use a class from the java.util.concurrent
package, how can you guarantee that you'll have no data loss in Clojure?
It's easy, atoms come to the rescue! Let's try this piece of code:
(clojure.core/use 'co.paralleluniverse.pulsar.core) (def events (atom [])) (defn log-events [count event-id] (dotimes [_ count] (swap! events conj event-id)...