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
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-
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
acquisition modes defined by
Lock
, providing more flexibility for dealing with lock unavail-
ability than does
synchronized
.