AtomicReference

Java AtomicReference Example

This is an example of the AtomicReference class of Java. It is another class under the java.util.concurrent.atomic package, which provides 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.

In the example below, we have created two threads that try to update the values of a String object, message and a custom class object, Person. They also update two AtomicReference objects, one created for the message, and the other one created for the person object.

The AtomicReference class provides a few methods in order to update the referenced object. Below, we make use of them:

  • The compareAndSet(V expect, V update) API method atomically sets the value to the given updated value, only if the current value is equal to the expected value.
  • The getAndSet(V newValue) API method atomically sets to the given value and returns the old value.
  • The lazySet(V newValue) API method eventually sets to the given value.
  • The set(V newValue) API method sets to the given value.
  • The get() API method gets the current value.

AtomicReferenceExample.java:

package com.javacodegeeks.snippets.core;

import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceExample {

	private static String message;
	private static Person person;
	private static AtomicReference<String> aRmessage;
	private static AtomicReference<Person> aRperson;
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new MyRun1());
		Thread t2 = new Thread(new MyRun2());
		message = "hello";
		person = new Person("Phillip", 23);
		aRmessage = new AtomicReference<String>(message);
		aRperson = new AtomicReference<Person>(person);
		System.out.println("Message is: " + message
				+ "\nPerson is " + person.toString());
		System.out.println("Atomic Reference of Message is: " + aRmessage.get()
				+ "\nAtomic Reference of Person is " + aRperson.get().toString());
		t1.start();
		t2.start();
		t1.join();
		t2.join();	
		System.out.println("\nNow Message is: " + message 
				+ "\nPerson is " + person.toString());
		System.out.println("Atomic Reference of Message is: " + aRmessage.get()
				+ "\nAtomic Reference of Person is " + aRperson.get().toString());
	}
		
	static class MyRun1 implements Runnable {

		public void run() {
			aRmessage.compareAndSet(message, "Thread 1");
			message = message.concat("-Thread 1!");
			person.setAge(person.getAge()+1);
			person.setName("Thread 1");
			aRperson.getAndSet(new Person("Thread 1", 1));
			System.out.println("\n" + Thread.currentThread().getName() +" Values " 
					+ message + " - " + person.toString());
			System.out.println("\n" + Thread.currentThread().getName() +" Atomic References " 
					+ message + " - " + person.toString());
		}		
	}
	
	static class MyRun2 implements Runnable {

		public void run() {
			message = message.concat("-Thread 2");
			person.setAge(person.getAge()+2);
			person.setName("Thread 2");
			aRmessage.lazySet("Thread 2");
			aRperson.set(new Person("Thread 2", 2));
			System.out.println("\n" + Thread.currentThread().getName() +" Values: " 
					+ message + " - " + person.toString());
			System.out.println("\n" + Thread.currentThread().getName() +" Atomic References: " 
					+ aRmessage.get() + " - " + aRperson.get().toString());
		}		
	}
	
	static 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;
		}	
		
		@Override
		public String toString() {
			return "[name " + this.name + ", age " + this.age + "]";
		}
	}
	
}

If you run the example, you will see how the atomic reference objects are updated in a more consistent way.

Message is: hello
Person is [name Phillip, age 23]
Atomic Reference of Message is: hello
Atomic Reference of Person is [name Phillip, age 23]

Thread-1 Values: hello-Thread 2-Thread 1! - [name Thread 1, age 26]

Thread-0 Values hello-Thread 2-Thread 1! - [name Thread 1, age 26]

Thread-1 Atomic References: Thread 2 - [name Thread 1, age 1]

Thread-0 Atomic References hello-Thread 2-Thread 1! - [name Thread 1, age 26]

Now Message is: hello-Thread 2-Thread 1!
Person is [name Thread 1, age 26]
Atomic Reference of Message is: Thread 2
Atomic Reference of Person is [name Thread 1, age 1]

 
This was an example of the AtomicReference class of Java.

Download
You can download the full source code of this example here: JavaAtomicReferenceExample.zip

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Alexander
Alexander
5 years ago

Thanks for the example:)
Could you fix the mistake please:
at line 44 should be the same as at line 59

Back to top button