Java Concurrency: AtomicReference

August 12, 2019

Category: The package java.util.concurrent.atomic

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 to 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 from GitHub here.

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 till 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 if using a volatile variable is thread-safe, created in line 10 and 11. I start those two threads, line 12 and 13. And then wait till both are ended using thread join, line 14 and 15. After both threads are stopped I check 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.assertTrue(
	at org.junit.Assert.assertTrue(

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 the method updates the value to the new value and return 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 lead to race conditions since for specific thread interleavings a thread overwrites the computation of the 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.

Make your application thread safe