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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. Languages
  4. How AtomicReference Works

How AtomicReference Works

Here's a look at atomicity and the role it plays in Java concurrent APIs. See how various atomic properties help keep data accurate.

Sandeep Rawat user avatar by
Sandeep Rawat
·
Aug. 25, 16 · Tutorial
Like (5)
Save
Tweet
Share
22.38K Views

Join the DZone community and get the full member experience.

Join For Free

This article will cover the AtomicReference and AtomicStampedReference properties of a Java concurrent API.

Atomicity

If you look up the meaning of atomic, you will get the answer 'whole'. So an atomic operation is supposed to be completed wholly or not at all. Other threads will not be able to see the operation "in progress" as it will never be viewed in a partially completed state due to its CAS (Compare and Swap) principle, which is the one machine (CPU) instruction. The memory effects for accesses and updates of atomics generally follow the rules for volatiles happen-before conditions. So another advantage is ‘no context switching’ or one can say ‘Thread-Safe’.

AtomicReference

Like AtomicInteger, AtomicLong, etc. we can have an atomic object as well — AtomicReference, which provides various utility methods to perform atomic operations. Take an example:

import java.util.concurrent.atomic.AtomicReference;

public class AtomicRefEg {

    static AtomicReference<Person> p  = new AtomicReference<Person>(new Person(20));
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable(){
            @Override
            public void run() {
                for(int i=1 ; i<=3 ; i++){
                    p.set(new Person(p.get().age+10));
                    System.out.println("Atomic Check by first thread: "+Thread.currentThread().getName()+" is "+p.get().age);
                }
            }
        });
        Thread t2 = new Thread(new Runnable(){
            @Override
            public void run() {
                Person per = p.get();
                for(int i=1 ; i<=3 ; i++){
                    System.err.println(p.get().equals(per)+"_"+per.age+"_"+p.get().age);
                    p.compareAndSet(per, new Person(p.get().age+10));
                    System.out.println("Atomic Check by second thread : "+Thread.currentThread().getName()+" is "+p.get().age);
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Final value: "+p.get().age);
    }
}

class Person {
    int age;
    public Person(int i) {
        age=i;
    }
}


Output

Image title


As you see, how compareAndSet had worked here. It first checks whether the desired object matches an existing object or not, whereas a set method forcefully overrides the existing object. In the above example, the second thread is able to get matched with the existing object and when it could not, then it did not set the new value.

AtomicStampedReference

It adds one more fields to its constructor, which is the stamp. This stamp helps developers check whether any other thread trespassed the section and exited after making changes. It is a well-known A-B-A problem. The A-B-A problem is when a reference is changed from pointing to A, then to B, and then back to A. In the example below, the stamp value is being communicated between two threads.

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicRefEg {

    static int stampVal = 1;
    static AtomicStampedReference<Person> s  = new AtomicStampedReference<Person>(new Person(20), stampVal);
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable(){
            @Override
            public void run() {
                for(int i=1 ; i<=3 ; i++) {
                    System.out.println("stamp value for first thread:"+stampVal);
                    s.compareAndSet(s.getReference(), new Person(s.getReference().age+10), stampVal, ++stampVal);
                    System.out.println("Atomic Check by first thread: "+Thread.currentThread().getName()+" is "+s.getReference().age);
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=1 ; i<=3 ; i++){
                    System.out.println("stamp value for second thread:"+stampVal);
                    s.compareAndSet(s.getReference(), new Person(s.getReference().age+10), stampVal, ++stampVal);
                    System.out.println("Atomic Check by second thread : "+Thread.currentThread().getName()+" is "+s.getReference().age);
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Final value: "+s.getReference().age);
    }
}

class Person {
    int age;
    public Person(int i) {
        age=i;
    }
}


Output

Image title

Object (computer science) Atomicity (database systems) Memory (storage engine) Advantage (cryptography) Machine Central Authentication Service Java (programming language) dev Property (programming)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • ChatGPT: The Unexpected API Test Automation Help
  • AWS Cloud Migration: Best Practices and Pitfalls to Avoid
  • Real-Time Stream Processing With Hazelcast and StreamNative
  • Key Considerations When Implementing Virtual Kubernetes Clusters

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: