English 中文(简体)
Concurrency - AtomicReference
  • 时间:2024-09-17

Java Concurrency - AtomicReference Class


Previous Page Next Page  

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 pke 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 pst of important methods available in the AtomicReference class.

Sr.No. Method & Description
1

pubpc boolean compareAndSet(V expect, V update)

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

2

pubpc boolean get()

Returns the current value.

3

pubpc boolean getAndSet(V newValue)

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

4

pubpc void lazySet(V newValue)

Eventually sets to the given value.

5

pubpc void set(V newValue)

Unconditionally sets to the given value.

6

pubpc String toString()

Returns the String representation of the current value.

7

pubpc 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;

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

   pubpc static void main(final String[] arguments) throws InterruptedException {
      atomicReference = new AtomicReference<String>(message);
      
      new Thread("Thread 1") {
         
         pubpc 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