Java Reference
In-Depth Information
While the atomic scalar classes extend Number , they do not extend the primitive wrapper
classes such as Integer or Long . In fact, they cannot: the primitive wrapper classes are
immutable whereas the atomic variable classes are mutable. The atomic variable classes also
do not redefine hashCode or equals ; each instance is distinct. Like most mutable objects,
they are not good candidates for keys in hash-based collections.
15.3.1. Atomics as “Better Volatiles”
In Section 3.4.2 , we used a volatile reference to an immutable object to update multiple
state variables atomically. That example relied on check-then-act, but in that particular case
the race was harmless because we did not care if we occasionally lost an update. In most other
situations, such a check-then-act would not be harmless and could compromise data integrity.
For example, NumberRange on page 67 could not be implemented safely with a volat-
ile reference to an immutable holder object for the upper and lower bounds, nor with using
atomic integers to store the bounds. Because an invariant constrains the two numbers and
they cannot be updated simultaneously while preserving the invariant, a number range class
using volatile references or multiple atomic integers will have unsafe check-then-act se-
quences.
We can combine the technique from OneValueCache with atomic references to close the
race condition by atomically updating the reference to an immutable object holding the lower
and upper bounds. CasNumberRange in Listing 15.3 uses an AtomicReference to an
IntPair to hold the state; by using compareAndSet it can update the upper or lower
bound without the race conditions of NumberRange .
Search WWH ::




Custom Search