In our outline of how synchronization works, we saw that under the hood, a machine instruction generally called Compare-And-Swap (CAS) was used to effectively read and write to a memory location at the same time. From Java 5 onwards, CAS and related instructions are effectively exposed at the level of the Java programmer in the form of a series of "atomic" classes in the java.util.concurrent package:
- Classes providing atomic access to main primitive types or to an object reference: AtomicBoolean, AtomicInteger andAtomicLong, AtomicReference;
- Classes providing atomic access to fields in arrays of the correspoding types: AtomicIntegerArray, AtomicLongArray,AtomicReferenceArray;
- Classes to atomically couple a boolean or integer with a reference field: AtomicMarkableReference andAtomicStampedReference;
- Atomic field updaters: classes to wrap up atomic access, via reflection, to volatile fields of another class (AtomicIntegerFieldUpdater, AtomicLongFieldUpdater and AtomicReferenceFieldUpdater);
- Concurrent collection classes, including significantly a highly concurrent hash map implementation.
Article written by Neil Coffey (@BitterCoffey).