2020-06-08

Java - AtomicReference example

Java AtomicReference example

AtomicReference

An object reference that may be updated atomically.

The AtomicReference class provides reference objects that may be read and written atomically, so when multiple threads try to reach them at the same time, only one will be able to do so.

The following methods are provided:


  • compareAndSet(V expect, V update):Atomically sets the value to the given updated value if the current value == the expected value.
  • getAndSet(V newValue):Atomically sets to the given value and returns the old value.
  • lazySet(V newValue):Eventually sets to the given value.
  • set(V newValue):Sets to the given value.
  • get():Gets the current value.


Suppose there is a class Person, defined as follows:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "[name: " + this.name + ", age: " + this.age + "]";
    }
}
If you use ordinary object references, updating objects in a multithreaded situation may cause inconsistencies. For example:
The initial state of an object is name=Tom, age = 18.
In the thread 1 namemodified to Tom1, age + 1.
Thread 2 will be namemodified to Tom2, age + 2.

We believe that only two results will be produced:

If thread 1 executes first and thread 2 executes later, the intermediate state is name=Tom1, age = 19and the resulting state isname=Tom2, age = 21
If thread 2 executes first and thread 1 executes later, the intermediate state is name=Tom2, age = 20and the resulting state isname=Tom1, age = 21
But the possible output is as follows:

Person is [name: Tom, age: 18]
Thread2 Values [name: Tom1, age: 21]
Thread1 Values [name: Tom1, age: 21]
Now Person is [name: Tom1, age: 21]


private static Person person;

public static void main(String[] args) throws InterruptedException {
    person = new Person("Tom", 18);

    System.out.println("Person is " + person.toString());

    Thread t1 = new Thread(new Task1());
    Thread t2 = new Thread(new Task2());

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    System.out.println("Now Person is " + person.toString());
}

static class Task1 implements Runnable {
    public void run() {
        person.setAge(person.getAge() + 1);
        person.setName("Tom1");

        System.out.println("Thread1 Values "
                + person.toString());
    }
}

static class Task2 implements Runnable {
    public void run() {
        person.setAge(person.getAge() + 2);
        person.setName("Tom2");

        System.out.println("Thread2 Values "
                + person.toString());
    }
}
If you use atomic object references, updating objects in a multi-threaded environment can ensure consistency. E.g:


private static Person person;

private static AtomicReference<Person> aRperson;

public static void main(String[] args) throws InterruptedException {
    person = new Person("Tom", 18);
    aRperson = new AtomicReference<Person>(person);

    System.out.println("Atomic Person is " + aRperson.get().toString());

    Thread t1 = new Thread(new Task1());
    Thread t2 = new Thread(new Task2());

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    System.out.println("Now Atomic Person is " + aRperson.get().toString());
}

static class Task1 implements Runnable {
    public void run() {
        aRperson.getAndSet(new Person("Tom1", aRperson.get().getAge() + 1));

        System.out.println("Thread1 Atomic References "
                + aRperson.get().toString());
    }
}

static class Task2 implements Runnable {
    public void run() {
        aRperson.getAndSet(new Person("Tom2", aRperson.get().getAge() + 2));

        System.out.println("Thread2 Atomic References "
                + aRperson.get().toString());
    }
}
But the possible output is as follows:

Atomic Person is [name: Tom, age: 18]
Thread1 Atomic References [name: Tom1, age: 19]
Thread2 Atomic References [name: Tom2, age: 21]
Now Atomic Person is [name: Tom2, age: 21]

No comments:

Post a Comment