Explicit locks in Java 5 (ctd)
On the previous page, we introduced the notion of a
lock, used to manage
access to shared data.
Java 5 introduces classes that implement explicit locks.
Explicit locks are useful in cases where you need to overcome some of
the shortcomings of
built-in synchronization. In particular, they have the following features:
- A thread can attempt to acquire a lock interruptibly;
- A thread can give a timeout value for attempting to acquire the lock;
- Read/write locks are supported– that is, locks that allow multiple
concurrent readers if the lock is not locked for writing;
- The traditional wait/notify metaphor is extended to allow conditions
- Support for fairness (if more than one thread is waiting for
a lock, they acquire in first-in-first-out order when it becomes available);
- The ability to lock beyond the scope of a block: for example,
one method can pass a lock object to another thread;
- Locks can be queried to find out, for example, if they
currently have any threads waiting to acquire them.
The package java.util.concurrent.locks contains the various lock
classes and interfaces. The most significant of these to most applications are three
interfaces: Lock, ReadWriteLock, and
Condition, plus the two lock implementations ReentrantLock
and ReentrantReadWriteLock. (The package also contains a few other
abstract classes that are useful if you are implementing a new lock type; we
won't look at those here.)
On the next page, we look at an example of
using a Java 5 Lock instance.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.