DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Rethinking Recruitment: A Journey Through Hiring Practices
  • Fixing Common Oracle Database Problems
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  1. DZone
  2. Coding
  3. Java
  4. Java Concurrency: AtomicReference

Java Concurrency: AtomicReference

Want to learn more about concurrency in Java?

By 
Thomas Krieger user avatar
Thomas Krieger
·
Updated Jan. 16, 20 · Presentation
Likes (21)
Comment
Save
Tweet
Share
65.4K Views

Join the DZone community and get the full member experience.

Join For Free

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
    @Test
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:

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:

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

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 (programming language)

Published at DZone with permission of Thomas Krieger, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!