Java Reference
In-Depth Information
izations such as lock elision for thread-confined lock objects and lock coarsening to eliminate
synchronization with intrinsic locks (see Section 11.3.2 ) ; doing this with library-based locks
seems far less likely. Unless you are deploying on Java 5.0 for the foreseeable future and you
have a demonstrated need for ReentrantLock 's scalability benefits on that platform, it is
not a good idea to choose ReentrantLock over synchronized for performance reas-
ons.
13.5. Read-write Locks
ReentrantLock implements a standard mutual-exclusion lock: at most one thread at a
time can hold a ReentrantLock . But mutual exclusion is frequently a stronger locking
discipline than needed to preserve data integrity, and thus limits concurrency more than ne-
cessary. Mutual exclusion is a conservative locking strategy that prevents writer/writer and
writer/reader overlap, but also prevents reader/reader overlap. In many cases, data structures
are “read-mostly”—they are mutable and are sometimes modified, but most accesses involve
only reading. In these cases, it would be nice to relax the locking requirements to allow mul-
tiple readers to access the data structure at once. As long as each thread is guaranteed an up-
to-date view of the data and no other thread modifies the data while the readers are viewing
it, there will be no problems. This is what read-write locks allow: a resource can be accessed
by multiple readers or a single writer at a time, but not both.
ReadWriteLock , shown in Listing 13.6 , exposes two Lock objects—one for reading and
one for writing. To read data guarded by a ReadWriteLock you must first acquire the read
lock, and to modify data guarded by a ReadWriteLock you must first acquire the write
lock. While there may appear to be two separate locks, the read lock and write lock are simply
different views of an integrated read-write lock object.
Listing 13.6. ReadWriteLock Interface.
The locking strategy implemented by read-write locks allows multiple simultaneous readers
but only a single writer. Like Lock , ReadWriteLock admits multiple implementations
that can vary in performance, scheduling guarantees, acquisition preference, fairness, or lock-
ing semantics.
Search WWH ::




Custom Search