Java Concurrency: AtomicReference

DZone 's Guide to

Java Concurrency: AtomicReference

Want to learn more about concurrency in Java?

· Java Zone ·
Free Resource

Java.util.concurrent.atomic.AtomicReference is a class designed to update variables in a thread-safe way. Why do we need the class AtomicReference? Why can we not simply use a volatile variable? And how can we use it correctly?

Why AtomicReference?

For the tool I am writing, I need to detect if an object was called from multiple threads. I use the following immutable class for this:

public class State {
    private final Thread thread;
    private final boolean accessedByMultipleThreads;
    public State(Thread thread, boolean accessedByMultipleThreads) {
        this.thread = thread;
        this.accessedByMultipleThreads = accessedByMultipleThreads;
    public State() {
        this.thread = null;
        this.accessedByMultipleThreads = false;
    public State update() {
        if(accessedByMultipleThreads)   {
            return this;
        if( thread == null  ) {
            return new  State(Thread.currentThread()
            , accessedByMultipleThreads);
        if(thread != Thread.currentThread()) {
            return new  State(null,true);
        return this;
    public boolean isAccessedByMultipleThreads() {
        return accessedByMultipleThreads;

You can download the source code of all examples on GitHub.

I store the first thread accessing an object in the variable thread, line 2. When another thread accesses the object, I set the variable accessedByMultipleThreads to true and the variable thread to null, line 23. When the variable accessedByMultipleThreads is true, I do not change the state, line 15 until 17.

I use this class in every object to detect if it was accessed by multiple threads. The following example uses the state in the class UpdateStateNotThreadSafe:

public class UpdateStateNotThreadSafe {
    private volatile  State state = new State();
    public void update() {
        state = state.update();
    public State getState() {
        return state;

I store the state in the volatile variable state, line 2. I need the volatile keyword to make sure that the threads always see the current values, as explained in greater detail here.

To check if using a volatile variable is thread-safe, I use the following test:

public class ConcurrencyTestUpdateState {
    private final UpdateStateNotThreadSafe object = 
        new UpdateStateNotThreadSafe();
    private void update() {
    public void test() throws InterruptedException {
        Thread first = new Thread( () ->    {  update();  } ) ;
        Thread second = new Thread( () ->   {  update();  } ) ;
        assertTrue(  object.getState().isAccessedByMultipleThreads() );

I need two threads to test using a volatile variable that is thread-safe, which is created in lines 10 and 11. I start those two threads, line 12 and 13. And then, I wait until both are ended using thread join, lines 14 and 15. After both threads are stopped, I check to see if the flag accessedByMultipleThreads is true, line 16.

To test all thread interleavings, I use the annotation Interleave, line 4, from vmlens. The Interleave annotation tells vmlens to test all thread interleavings for the annotated method. Running the test, I see the following error:

    at org.junit.Assert.fail(Assert.java:91)
    at org.junit.Assert.assertTrue(Assert.java:43)
    at org.junit.Assert.assertTrue(Assert.java:54)

The vmlens report shows what went wrong:

Image title

The problem is that for a specific thread interleaving both threads first read the state. So, one thread overwrites the result of the other thread.

How to Use AtomicReference?

To solve this race condition, I use the compareAndSet method from AtomicReference.

The compareAndSet method takes two parameters, the expected current value and the new value. The method atomically checks if the current value equals the expected value. If yes, then the method updates the value to the new value and returns true. If not, the method leaves the current value unchanged and returns false.

The idea to use this method is to let compareAndSet check if the current value was changed by another thread while we calculated the new value. If not, we can safely update the current value. Otherwise, we need to recalculate the new value with the changed current value.

The following shows how to use the compareAndSet method to atomically update the state:

public class UpdateStateWithCompareAndSet {
    private final AtomicReference<State> state = 
            new AtomicReference<State>(new State());
    public  void update() {
        State current = state.get();
        State newValue = current.update();
        while( ! state.compareAndSet( current , newValue ) ) {
            current = state.get();
            newValue = current.update();
    public State getState() {
        return state.get();

I now use an AtomicReference for the state, line 2. To update the state, I first need to get the current value, line 5. Then, I calculate the new value, line 6, and try to update the AtomicReference using compareAndSet, line 7. If the update succeeds, I am done. If not, I need to get the current value again, line 8, and recalculate the new value, line 9. Then, I can try again to update the AtomicReference using compareAndSet. I need a while loop since the compareAndSet might fail multiple times.


Using volatile variables leads to race conditions since specific thread interleavings for a thread overwrites the computation of other threads. By using the compareAndSet method from the class AtomicReference, we can circumvent this race condition. We atomically check if the current value is still the same as when we started the computation. If yes, we can safely update the current value. Otherwise, we need to recalculate the new value with the changed current value.

java ,concurency ,atomic classes ,atomicreference ,reference ,class ,atomic ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}