Think about this scenario: you have a series of concurrent tasks, for example 10 threads each of them responsible download a web page with a URL. When finished you save them to somewhere like a database. But you don't want save them one by one, you want save them as one SQL statement, so you can not do database .
The future is a macro defined in clojure.core, one of concurrency primitives. This macro create a future object for a body of expression. The future object is a Reference Type, you can dereference it later by deref or @.
The expression body of the future will be executed in a new thread right after the creation of the future object and the result will be cached when thread complete. If the body expression takes a while to complete, then the deref will be blocked until the thread complete.The expression body of the future will be executed in a new thread right after the creation of the future .
The alter and commute are two ways to update a Ref type in a trasaction in Clojure. This post Clojure concurrency: Ref type and coordinate change example demonstrate how to use Ref type in a classic way.
The alter is pretty clear and easy to understand, it do the update operation based on the view of the world at the start of the transaction, this world is so called snapshot, the update operation itself has no contention, you can think of the operation itself is done in a way that the current thread is the only one which do the change. Thats STM all about, no lock, no race condition.The alter is pretty clear and easy to understand, it do the update operation based on the view of the world at the .
Clojure concurrency programming facilities provides four reference types: Ref, Agent, Atom, Var. Ref is designed for coordinate changes. Coordinate means two or more changes must happen as a whole or nothing should happen. The classic example is the transfer between bank account.
Lets define two bank account :