AtomicReferenceArray

Guide to working with AtomicReferenceArray.

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The official documentation of the AtomicReferenceArray states that it is an array of object references, that each one, may be updated atomically. However, it is easy to get confused with all the other array constructs and AtomicReferenceArray, so we’ll go through one by one to clarify the differences. Also, according to the Java specification, assignments in Java except for primitive types long and double are atomic, which may confuse the reader as to what does atomically updating an element of an AtomicReferenceArray instance means?

Remember to draw a distinction between assignment and update of an atomic variable. Assignment involves changing the reference (memory location) pointed to by an atomic variable e.g.

        // first assignment
        AtomicReference<Object> atomicReference = new AtomicReference<>(null);

        // assigning a different AtomicReference object
        atomicReference = new AtomicReference<>(Long.class);

Updating atomically, implies that the value of an atomic variable holds is changed based on an expected value the variable currently holds e.g.

        // first assignment
        AtomicReference<Object> atomicReference = new AtomicReference<>(null);

        // atomic update
        atomicReference.compareAndSet(null, Long.class);

The atomic update has consequences for memory visibility and establishes the happens-before relationship as we’ll learn shortly. In contrast, an assignment operation may not establish a happens-before relationship if the variable isn’t marked volatile.

Array Reference

...