concept lock in category clojure

appears as: locks, lock, locks, lock
The Joy of Clojure, Second Edition

This is an excerpt from Manning's book The Joy of Clojure, Second Edition.

Within the first few moments of using Clojure’s STM, you’ll notice something different than you may be accustomed to: no locks. Because there’s no need for ad hoc locking schemes when using STM, there’s no chance of deadlock. Likewise, Clojure’s STM doesn’t require the use of monitors and as a result is free from lost wakeup conditions. Behind the scenes, Clojure’s STM uses multiversion concurrency control (MVCC) to ensure snapshot isolation. In simpler terms, snapshot isolation means each transaction gets its own view of the data it’s interested in. This snapshot is made up of in-transaction reference values, forming the foundation of MVCC (Ullman 1988). As illustrated in figure 10.5, each transaction merrily chugs along making changes to in-transaction values only, oblivious to and ambivalent about other transactions. At the conclusion of the transaction, the local values are examined against the modification target for conflicts. An example of a simple possible conflict is if another transaction B committed a change to a target reference during the time that transaction A was working, thus causing A to retry. If no conflicts are found, then the in-transaction values are committed (set as the final value) and the target references are modified with their updated values. Another advantage that STM provides is that in the case of an exception during a transaction, the in-transaction values are thrown away and the exception is propagated outward. In the case of lock-based schemes, exceptions can complicate matters, because in most cases locks need to be released (and in some cases, in the correct order) before an exception can be safely propagated up the call stack.

Figure 10.5. Illustrating an STM retry: Clojure’s STM works much like a database.

Because each transaction has its own isolated snapshot, there’s no danger in retrying—the data is never modified until a successful commit occurs. STM transactions can easily nest without taking additional measures to facilitate composition. In languages that provide explicit locking for concurrency, matters of composability are often difficult, if not impossible. The reasons for this are far-reaching, and the mitigating forces (Goetz 2006) are complex, but the primary reasons tend to be because lock-based concurrency schemes often hinge on a secret incantation not explicitly understandable through the source itself: for example, the order in which to take and release a set of locks.

Java provides a set of explicit locks in the java.util.concurrent.locks package. One such lock is provided by the java.util.concurrent.locks.ReentrantLock class. You can create a new type of smart array that provides finer-grained locking on a per-slot basis. Rather than using one lock per array element, you can use a small pool of locks to conserve resources. To accomplish this, first let’s create a useful function called lock-i:

(defn lock-i [target-index num-locks]   (mod target-index num-locks)) #1 #1 - Calculation falls within 0 and num-locks !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":45}]]"} !@%STYLE%@!

The lock-i function has one purpose: to calculate a lock number based solely on the array index in question and the total size of the target array. A simple way to stripe an array is to use the classic index modulo array_size formula. The function that uses lock-i is shown next.

Listing 10.9. Implementing SafeArray using ReentrantLock
(import 'java.util.concurrent.locks.ReentrantLock) (defn make-smart-array [t sz]   (let [a   (make-array t sz) #1         Lsz (/ sz 2)         L   (into-array (take Lsz #2                         (repeatedly #(ReentrantLock.))))]     (reify       SafeArray       (count [_] (clj/count a))       (seq [_] (clj/seq a))       (aget [_ i]         (let [lk (clj/aget L (lock-i (inc i) Lsz))]           (.lock lk) #3           (try             (clj/aget a i)             (finally (.unlock lk))))) #4       (aset [this i f]         (let [lk (clj/aget L (lock-i (inc i) Lsz))]           (.lock lk)           (try             (clj/aset a                       i                       (f (aget this i))) #5              (finally (.unlock lk)))))))) #1 - Array #2 - Locks, one for every two array slots #3 - Explicit locking #4 - Explicit unlocking #5 - Reentrant locking on nested get call !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!

The first point of note is that you use a technique (simplified for clarity) called lock striping (Herlihy 2008) to reduce the contention of guarding the array as a whole using locking. The target array a’s slots are guarded by a number of locks equal to half its size, each chosen using the simple formula (mod target-index num-locks). This scheme allows readers and writers to (potentially) act independently when accessing different array slots. It’s crucial that you close over the lock instance array L, because for explicit locks to work, each access must lock and unlock the same instance. Additionally, you call the .unlock method in the body of a finally expression, because failing to do so is a recipe for disaster. Unlike the locking macro, the ReentrantLock class doesn’t manage lock release automatically. Observe the following smart array in action:

No need for locks

In applications of any size, the inclusion of locks for managing concurrent access to shared data adds complexity. Many factors add to this complexity, but chief among them are the following:

  • You can’t use locks without supplying extensive error handling. This is critical in avoiding orphaned locks (locks held by a thread that has died).