Author: Paul Butcher
Pub Date: 2014
Size: 10 Mb
Your software needs to leverage multiple cores, handle thousands of users and terabytes of data, and continue working in the face of both hardware and software failure. Concurrency and parallelism are the keys, and Seven Concurrency Models in Seven Weeks equips you for this new world. See how emerging technologies such as actors and functional programming address issues with traditional threads and locks development. Learn how to exploit the parallelism in your computer’s GPU and leverage clusters of machines with MapReduce and Stream Processing. And do it all with the confidence that comes from using tools that help you write crystal clear, high-quality code.
As we’ll see,
Clojure’smutable variables allow us to handle real-world side effects while remaining safe and consistent. Today we’ll see how Clojure’s mutable variables work in concert with persistent data structures to separate identity from state. This allows multiple threads to access mutable variables concurrently without locks (and the associated danger of deadlock) and without any of the problems of escaped or hidden
mutable state that we saw in The Perils of Mutable State, on page 50. We’ll start by looking at what is arguably the simplest of Clojure’s mutable variable types, the atom.
At first glance, this looks like it should be thread-safe—playersis privateand accessed only via the addPlayer()and getPlayerIterator()methods, both of which are synchronized. Unfortunately, it is not thread-safe because the iterator returned by getPlayerIterator()still references the mutable state contained within players—if another thread calls addPlayer()while the iterator is in use, we’ll see a ConcurrentModificationExceptionor worse. The state has escapedfrom the protection provided by T ournament.
Hidden and escaped state are just two of the dangers of mutable state in concurrent programs—there are plenty of others. These dangers would disappear if we could find a way to avoid mutable state entirely, which is exactly what functional programming enables us to do.
A Whirlwind Tour of Clojure It takes only a few minutes to get the hang of Clojure’s Lisp syntax. The easiest way to experiment with Clojure is through its REPL(read-evaluateprint loop), which you can start with lein repl(leinis the standard Clojure build tool). This allows you to type code and have it evaluated immediately without having to create source files and compile them, which can be amazingly helpful when experimenting with unfamiliar code. When the REPLstarts, you should see the following prompt: