Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How AtomicReference Works

DZone's Guide to

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.

· Integration Zone
Free Resource

The Integration Zone is brought to you in partnership with Cloud Elements. What's below the surface of an API integration? Download The Definitive Guide to API Integrations to start building an API strategy.

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

Your API is not enough. Learn why (and how) leading SaaS providers are turning their products into platforms with API integration in the ebook, Build Platforms, Not Products from Cloud Elements.

Topics:
java ,concurency ,atomicity

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}