Java Concurrency - AtomicReference Class



A java.util.concurrent.atomic.AtomicReference class provides operations on underlying object reference that can be read and written atomically, and also contains advanced atomic operations. AtomicReference supports atomic operations on underlying object reference variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

AtomicReference Methods

Following is the list of important methods available in the AtomicReference class.

Sr.No. Method & Description
1

public boolean compareAndSet(V expect, V update)

Atomically sets the value to the given updated value if the current value == the expected value.

2

public boolean get()

Returns the current value.

3

public boolean getAndSet(V newValue)

Atomically sets to the given value and returns the previous value.

4

public void lazySet(V newValue)

Eventually sets to the given value.

5

public void set(V newValue)

Unconditionally sets to the given value.

6

public String toString()

Returns the String representation of the current value.

7

public boolean weakCompareAndSet(V expect, V update)

Atomically sets the value to the given updated value if the current value == the expected value.

Example

The following TestThread program shows usage of AtomicReference variable in thread based environment.

import java.util.concurrent.atomic.AtomicReference;

public class TestThread {
   private static String message = "hello";
   private static AtomicReference<String> atomicReference;

   public static void main(final String[] arguments) throws InterruptedException {
      atomicReference = new AtomicReference<String>(message);
      
      new Thread("Thread 1") {
         
         public void run() {
            atomicReference.compareAndSet(message, "Thread 1");
            message = message.concat("-Thread 1!");
         };
      }.start();

      System.out.println("Message is: " + message);
      System.out.println("Atomic Reference of Message is: " + atomicReference.get());
   }
}

This will produce the following result.

Output

Message is: hello
Atomic Reference of Message is: Thread 1
Advertisements