Java Reference
In-Depth Information
The
Callable
interface defines a task that can return a result (unlike
a
Runnable
). A
Future
represents a computationsuch as that in a
Callable
that may not yet have completed or even begun. You can submit
a
Future
to an
Executor
(using the concrete
FutureTask
class) knowing that
at some time in the future the result of the computation will be avail-
able. You can use the
Future
to ask whether the task has completed or
to block until the task completes and the result is available.
The
java.util.concurrent.locks
subpackage defines the
Lock
and
Condi-
tion
interfaces and the
ReentrantLock
implementation.
Lock
abstracts the
functionality of locking, as implied in the use of
synchronized
blocks and
methods, to allow more flexible locking. A
Lock
can be locked in one
method and unlocked in a different onesomething that is needed in
some concurrent traversal algorithms, and which is impossible to do
with
synchronized
blocks or methods. In addition, the methods of
Lock
al-
low you to acquire the lock only if it is availablethat is, you don't block
trying to acquire the lockor to stop trying to acquire the lock if interrup-
ted or if a certain time has elapsed.
A
Condition
abstracts the functionality of the
Object
monitor methods
wait
,
notify
, and
notifyAll
into a distinct interface with methods
await
,
signal
, and
signalAll
.
Condition
objects are used with
Lock
objects the
same way that
wait
/
notify
are used with monitors. The advantage is that
while there is only a single wait-set per object, a
Lock
can have as many
associated
Condition
objects as you need. The
ReentrantLock
class is one
useful implementation of
Lock
that gives you
Condition
objects that are
functionally equivalent to
synchronized
methods and blocks, plus the use
of the monitor methods.
The package also contains the
ReadWriteLock
interfaceand an implement-
ationfor a lock that allows for both exclusive use and shared useinform-
ally, only one writer may hold the lock (exclusive) but arbitrarily many
readers can hold the lock (shared).
The
java.util.concurrent.atomic
package provides classes that repres-
ents values (
int
,
long
, references, and arrays of these values) that
can be manipulated atomically. These classes provide operations that
without the use of locks or in-built synchronization can, for example,