▪ If access to a resource is uncontended, then CAS-based protection will be slightly faster
than traditional synchronization (though no protection at all will be slightly faster still).
▪ If access to a resource is lightly or moderately contended, CAS-based protection will be
faster (often much faster) than traditional synchronization.
▪ As access to the resource becomes heavily contended, traditional synchronization will at
some point become the more efficient choice. In practice, this occurs only on very large
machines running a large number of threads.
▪ CAS-based protection is not subject to contention when values are read and not written.
JAVA 8 AND CONTENDED ATOMIC CLASSES
Classes in the java.util.concurrent.atomic package use CAS-based primitives instead of tra-
ditional synchronization. As a result, performance of those classes (for example, the AtomicLong
class) tends to be faster than writing a synchronized method to increment a long variable—at least
until the contention for the CAS primitive becomes too high.
Java 8 introduces a number of classes to address this: atomic adders and accumulators (for ex-
ample, the LongAdder class). These classes are more scalable than the traditional atomic classes.
When multiple threads update a LongAdder , the class can hold the updates separately for each
thread. That means the threads needn't wait for each other to complete their operation; instead,
the values are stored in (essentially) an array and each thread can return quickly. Later, the values
will be added or accumulated when some thread attempts to retrieve the current value.
Under little or no contention, the value is accumulated as the program runs, and the behavior of
the adder will be the same as that of the traditional atomic class. Under severe contention, the up-
dates will be much faster, though the instance will start to use more memory to store the array of
values. Retrieval of a value in that case will also be slightly slower since it must process all the
pending updates in the array. Still, under very contended conditions, these new classes will per-
form even better than their atomic counterparts.
In the end, there is no substitute for extensive testing under the actual production conditions
where the code will run: only then can a definite statement be made as to which implementa-
tion of a particular method is better. Even in that case, the definite statement applies only to