Good Fences Make Happy Threads

Fortunately, all is not lost. As I say, race conditions happen when you have more than one thread trying to modify the same data structure. So our first line of defense is to make sure that our threads don’t accidentally change a shared resource. And this brings us back to Clojure’s immutable data structures.

Recall that once you make a Clojure vector or list or map or set you cannot change it: you can only make modified copies. In general, immutable data structures are a huge help in crafting understandable programs. But mix in some threads, and the immutability becomes almost indispensable. Take this book inventory for example:

 (​def​ inventory [{:title ​"Emma"​ :sold 51 :revenue 255}
  {:title ​"2001"​ :sold ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.