Java 併發 - AtomicReference 類



java.util.concurrent.atomic.AtomicReference 類提供對底層物件引用的操作,這些操作可以以原子方式讀取和寫入,並且還包含高階原子操作。AtomicReference 支援對底層物件引用變數的原子操作。它具有 get 和 set 方法,這些方法的工作方式類似於對 volatile 變數的讀寫。也就是說,set 與隨後對同一變數的任何 get 之間存在 happens-before 關係。原子 compareAndSet 方法也具有這些記憶體一致性特性。

AtomicReference 方法

以下是 AtomicReference 類中可用的一些重要方法列表。

序號 方法及描述
1

public boolean compareAndSet(V expect, V update)

如果當前值 == 預期值,則以原子方式將值設定為給定的更新值。

2

public boolean get()

返回當前值。

3

public boolean getAndSet(V newValue)

以原子方式設定為給定值並返回先前的值。

4

public void lazySet(V newValue)

最終設定為給定值。

5

public void set(V newValue)

無條件設定為給定值。

6

public String toString()

返回當前值的字串表示形式。

7

public boolean weakCompareAndSet(V expect, V update)

如果當前值 == 預期值,則以原子方式將值設定為給定的更新值。

示例

以下 TestThread 程式展示了在基於執行緒的環境中使用 AtomicReference 變數。

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());
   }
}

這將產生以下結果。

輸出

Message is: hello
Atomic Reference of Message is: Thread 1
廣告