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:

Java







x 30



1 public class State { 2 private final Thread thread ; 3 private final boolean accessedByMultipleThreads ; 4 public State ( Thread thread , boolean accessedByMultipleThreads ) { 5 super (); 6 this . thread = thread ; 7 this . accessedByMultipleThreads = accessedByMultipleThreads ; 8 } 9 public State () { 10 super (); 11 this . thread = null ; 12 this . accessedByMultipleThreads = false ; 13 } 14 public State update () { 15 if ( accessedByMultipleThreads ) { 16 return this ; 17 } 18 if ( thread == null ) { 19 return new State ( Thread . currentThread () 20 , accessedByMultipleThreads ); 21 } 22 if ( thread != Thread . currentThread ()) { 23 return new State ( null , true ); 24 } 25 return this ; 26 } 27 public boolean isAccessedByMultipleThreads () { 28 return accessedByMultipleThreads ; 29 } 30 }









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 :

Java







xxxxxxxxxx 1



1 public class UpdateStateNotThreadSafe { 2 private volatile State state = new State (); 3 public void update () { 4 state = state . update (); 5 } 6 public State getState () { 7 return state ; 8 } 9 }









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:

Java







x 19



1 import com . vmlens . api . AllInterleavings ; 2 public class TestNotThreadSafe { 3 4 public void test () throws InterruptedException { 5 try ( AllInterleavings allInterleavings = 6 new AllInterleavings ( "TestNotThreadSafe" );) { 7 while ( allInterleavings . hasNext ()) { 8 final UpdateStateNotThreadSafe object = new UpdateStateNotThreadSafe (); 9 Thread first = new Thread ( () -> { object . update (); } ) ; 10 Thread second = new Thread ( () -> { object . update (); } ) ; 11 first . start (); 12 second . start (); 13 first . join (); 14 second . join (); 15 assertTrue ( object . getState (). isAccessedByMultipleThreads () ); 16 } 17 } 18 } 19 }





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

To test all thread interleavings we put the complete test in a while loop iterating over all thread interleavings using the class AllInterleavings from vmlens, line 7. Running the test I see the following error:

Java







xxxxxxxxxx 1



1 java . lang . AssertionError : 2 at org . junit . Assert . fail ( Assert . java : 91 ) 3 at org . junit . Assert . assertTrue ( Assert . java : 43 ) 4 at org . junit . Assert . assertTrue ( Assert . java : 54 )









The vmlens report shows what went wrong:

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:

Java xxxxxxxxxx 1 16 1 public class UpdateStateWithCompareAndSet { 2 private final AtomicReference < State > state = 3 new AtomicReference < State > ( new State ()); 4 public void update () { 5 State current = state . get (); 6 State newValue = current . update (); 7 while ( ! state . compareAndSet ( current , newValue ) ) { 8 current = state . get (); 9 newValue = current . update (); 10 } 11 } 12 public State getState () { 13 return state . get (); 14 } 15 } 16

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.

As Grzegorz Borczuch pointed out in a comment to this article there is since JDK 1.8 an easier to use method in AtomicReference which achieves the same result: updateAndGet. This method internally uses compareAndSet using a while loop to

update the AtomicReference.

Conclusion