Book Image

Clojure Data Analysis Cookbook - Second Edition

By : Eric Richard Rochester
Book Image

Clojure Data Analysis Cookbook - Second Edition

By: Eric Richard Rochester

Overview of this book

Table of Contents (19 chapters)
Clojure Data Analysis Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Getting better performance with commute


The STM system we created in the first 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...