|
Explicit locks in Java 5 (ctd)
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
(see below);
- 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.
Unless otherwise stated, the Java programming articles and tutorials on this site are written by Neil Coffey.
Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles,
or if you simply have a programming question that you would like to see answered on this site. Most topics
will be considered. But in particular, the site aims to provide tutorials and information on topics that
aren't well covered elsewhere, or on Java performance information that is poorly described or understood.
Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Javamex UK 2009. All rights reserved.
|