AtomicReference

Complete guide to understanding and effectively working with AtomicReference class. Learn the differences among atomic assignment of references in Java, volatile variables and the AtomicReference class.

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

Overview

A reference type is a data type that represents an instance of a Java class, i.e. it is a type other than one of the Java’s primitive types. For instance:

Long myLong = new Long(5);

In the above snippet the variable myLong represents a reference type. When we create the above object myLong, Java allocates appropriate memory for the object to be stored. The variable myLong points to this address in the memory, which stores the object. The address of the object in the memory is called the reference. Consider the below snippet:

Long myLong = new Long(5);
Long otherLong = myLong;

The two variables myLong and otherLong both point to the same memory location where the Long object is stored or we can say both variables are assigned the same reference (address) to the object but not the object itself.

Given the above context, it becomes easier to understand the AtomicReference class. According to the official documentation, AtomicReference allows us to atomically update the reference to an object. Before we further delve into the topic, we’ll first clarify the distinction between AtomicReference and assignment of references atomically in Java.

Atomic assignment of references in Java

Consider the following snippet:

class SomethingUseful {
   Thread thread;
   int myInt;
   HashMap<String, String> map;
   double myDouble;
   long myLong;

    void usefulFunction(int passedInt, long passedLong, double passedDouble, HashMap<String, String> passedMap) {
        thread = Thread.currentThread();
        myInt = passedInt;
        map = passedMap;
    }

}

If the method usefulFunciton() is invoked by several threads, can we see garbage values for the variables of an instance of class SomethingUseful? In the method usefulFunciton() there are two primitive type assignments and two reference assignments. The following holds true for assignments in Java as per the language specification:

  • All reference assignments are atomic. This doesn’t mean our method usefulFunction() is thread-safe. It just means that when a thread assigns the variables map or the thread, the assignment is ...