Java Reference
In-Depth Information
Chapter 13. Explicit Locks
Before Java 5.0, the only mechanisms for coordinating access to shared data were syn-
chronized and volatile . Java 5.0 adds another option: ReentrantLock . Contrary to
what some have written, ReentrantLock is not a replacement for intrinsic locking, but
rather an alternative with advanced features for when intrinsic locking proves too limited.
13.1. Lock and ReentrantLock
The Lock interface, shown in Listing 13.1 , defines a number of abstract locking operations.
Unlike intrinsic locking, Lock offers a choice of unconditional, polled, timed, and interrupt-
ible lock acquisition, and all lock and unlock operations are explicit. Lock implementations
must provide the same memory-visibility semantics as intrinsic locks, but can differ in their
locking semantics, scheduling algorithms, ordering guarantees, and performance characterist-
ics. ( Lock.newCondition is covered in Chapter 14 . )
Listing 13.1. Lock Interface.
ReentrantLock implements Lock , providing the same mutual exclusion and memory-vis-
ibility guarantees as synchronized . Acquiring a ReentrantLock has the same memory
semantics as entering a synchronized block, and releasing a ReentrantLock has the
same memory semantics as exiting a synchronized block. (Memory visibility is covered
in Section 3.1 and in Chapter 16 .) And, like synchronized , ReentrantLock offers
reentrant locking semantics (see Section 2.3.2 ) . ReentrantLock supports all of the lock-
acquisition modes defined by Lock , providing more flexibility for dealing with lock unavail-
ability than does synchronized .
Search WWH ::




Custom Search