Chapter 6. State and the concurrent world
This chapter covers
- The problems with mutable state
- Clojure’s approach to state
- Refs, agents, atoms, and vars
- Futures and promises
State—you’re doing it wrong.
Rich Hickey[1]
1From a presentation at the Boston Lisp meeting, 2012, http://www.youtube.com/watch?v=7mbcYxHO0nM&t=00h21m04s.
The preceding quote is from a presentation by Rich Hickey in which he discusses Clojure’s approach to concurrency and state. He means that most languages use an approach to modeling state that doesn’t work very well. To be precise, it used to work when computers were less powerful and ran programs in a single-threaded fashion, but in today’s world of increasingly multicore and multi-CPU computers, the model has broken down. This is evidenced by the difficulty of writing bug-free multithreaded code in typical object-oriented (OO) languages like Java and C++. Still, programmers continue to make the attempt, because today’s demands on software require that it take advantage of all available CPU cores. As software requirements grow in complexity, parallelism is becoming an implicit requirement.
This chapter is about concurrent programs and the problems they face in dealing with state. We’ll first examine what these problems are and then look at the traditional solutions. We’ll then look at Clojure’s approach to dealing with these issues and show that when trying to solve difficult problems, it’s sometimes worth starting with a fresh slate.