Database Reference
In-Depth Information
F Next, we block until each agent is done by calling await , and we dereference each
to get its value (both of these take place inside force-val ). Once we have the data
from each agent, we merge them all together into one hashmap:
(apply merge-with + (map force-val agents))))
See also
F Agents and asynchronous actions in the Clojure documentation ( http://clojure.
org/agents ) for more on agents.
Getting better performance with commute
The STM system we created in the irst recipe of this chapter, Managing program complexity
with STM , has one subtle problem: threads attempting to reference and update total-hu
and total-fams contend for these two values unnecessarily. Since everything comes down
to accessing these two resources, a lot of tasks are probably retried.
But they don't need to be. Both are simply updating those values with commutative functions
( #(+ sum-? %) ). The order in which these updates are applied doesn't matter. Since we
block until all of the processing is done, we don't have to worry about the two references
getting out of sync. They'll get back together eventually, before we access their values, and
that's good enough for this situation.
To update references with a commutative function, instead of alter , we use commute .
The alter function updates the references on the spot, while commute queues the update
to happen later, when the reference isn't otherwise engaged. This prevents contentions on
those references and can make the system faster too.
For this recipe, we'll again look at the problem we did in the Managing program complexity
with STM recipe.
Getting ready
Everything is going to be the same as it was for Managing program complexity with STM .
We'll use the same dependencies and requirements and even most of the functions as we
did for that recipe.
 
Search WWH ::




Custom Search