Java Reference
In-Depth Information
and reference types; these atomic variable classes are used, directly or indirectly, to imple-
ment most of the classes in java.util.concurrent .
15.3. Atomic Variable Classes
Atomic variables are finer-grained and lighter-weight than locks, and are critical for im-
plementing high-performance concurrent code on multiprocessor systems. Atomic variables
limit the scope of contention to a single variable; this is as finegrained as you can get (assum-
ing your algorithm can even be implemented using such fine granularity). The fast (uncon-
tended) path for updating an atomic variable is no slower than the fast path for acquiring a
lock, and usually faster; the slow path is definitely faster than the slow path for locks because
it does not involve suspending and rescheduling threads. With algorithms based on atomic
variables instead of locks, threads are more likely to be able to proceed without delay and
have an easier time recovering if they do experience contention.
The atomic variable classes provide a generalization of volatile variables to support atomic
conditional read-modify-write operations. AtomicInteger represents an int value, and
provides get and set methods with the same memory semantics as reads and writes to a
volatile int . It also provides an atomic compareAndSet method (which if successful has
the memory effects of both reading and writing a volatile variable) and, for convenience,
atomic add, increment, and decrement methods. AtomicInteger bears a superficial re-
semblance to an extended Counter class, but offers far greater scalability under contention
because it can directly exploit underlying hardware support for concurrency.
There are twelve atomic variable classes, divided into four groups: scalars, field updaters,
arrays, and compound variables. The most commonly used atomic variables are the scalars:
AtomicInteger , AtomicLong , AtomicBoolean , and AtomicReference . All
support CAS; the Integer and Long versions support arithmetic as well. (To simulate
atomic variables of other primitive types, you can cast short or byte values to and from
int , and use floatToIntBits or doubleToLongBits for floating-point numbers.)
The atomic array classes (available in Integer , Long , and Reference versions) are ar-
rays whose elements can be updated atomically. The atomic array classes provide volatile
access semantics to the elements of the array, a feature not available for ordinary arrays—a
volatile array has volatile semantics only for the array reference, not for its elements.
(The other types of atomic variables are discussed in Sections 15.4.3 and 15.4.4 .)
Search WWH ::




Custom Search