Java Concurrency: AtomicReference

January 07, 2020

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) {
		super();
		this.thread = thread;
		this.accessedByMultipleThreads = accessedByMultipleThreads;
	}
	public State() {
		super();
		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:

import com.vmlens.api.AllInterleavings;
public class TestNotThreadSafe {
	@Test
	public void test() throws InterruptedException {
		try (AllInterleavings allInterleavings = 
			new AllInterleavings("TestNotThreadSafe");) {
			while (allInterleavings.hasNext()) {	
		final UpdateStateNotThreadSafe object = new UpdateStateNotThreadSafe();		
		Thread first = new Thread( () ->    {  object.update();  } ) ;
		Thread second = new Thread( () ->   {  object.update(); } ) ;
		first.start();
		second.start();
		first.join();
		second.join();	
		assertTrue(  object.getState().isAccessedByMultipleThreads() );
			}
		}
	}
}

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.lang.AssertionError: 
	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:

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.

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

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.

testing multi-threaded applications on the JVM made easy

LEARN MORE

© 2020 vmlens Legal Notice Privacy Policy