Java Reference
In-Depth Information
15.4.3. Atomic Field Updaters
implementation is a bit different. Instead of representing each
Node
with an atomic referen-
ce,
ConcurrentLinkedQueue
uses an ordinary volatile reference and updates it through
Listing 15.8. Using Atomic Field Updaters in
ConcurrentLinkedQueue
.
The atomic field updater classes (available in
Integer
,
Long
, and
Reference
versions)
represent a reflection-based “view” of an existing volatile field so that CAS can be used on
existing volatile fields. The updater classes have no constructors; to create one, you call the
newUpdater
factory method, specifying the class and field name. The field updater classes
are not tied to a specific instance; one can be used to update the target field for any instance
of the target class. The atomicity guarantees for the updater classes are weaker than for the
regular atomic classes because you cannot guarantee that the underlying fields will not be
modified directly—the
compareAndSet
and arithmetic methods guarantee atomicity only
with respect to other threads using the atomic field updater methods.
In
ConcurrentLinkedQueue
, updates to the
next
field of a
Node
are applied using
the
compareAndSet
method of
nextUpdater
. This somewhat circuitous approach is
used entirely for performance reasons. For frequently allocated, short-lived objects like queue
link nodes, eliminating the creation of an
AtomicReference
for each
Node
is significant
enough to reduce the cost of insertion operations. However, in nearly all situations, ordin-
ary atomic variables perform just fine—in only a few cases will the atomic field updaters be