用於對「對象引用」進行原子操作,泛型參數 V 為引用類型。
boolean compareAndSet(V expect, V update)V getAndSet(V newValue)V get() / void set(V newValue)void lazySet(V newValue)public class AtomicReferenceimplements Serializable { private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; private volatile V value; // volatile 保證可見性 public final boolean compareAndSet(V expect, V update) { return unsafe.compareAndSwapObject(this, valueOffset, expect, update); } // ... 其他方法均基於 unsafe CAS 實現 }
兩大支柱:volatile 保證讀取最新值;Unsafe CAS 保證寫入原子性。
// AtomicReferenceTest.java
import java.util.concurrent.atomic.AtomicReference;
public class AtomicReferenceTest {
public static void main(String[] args) {
Person p1 = new Person(101), p2 = new Person(102);
AtomicReference ar = new AtomicReference(p1);
ar.compareAndSet(p1, p2); // 若當前為 p1 則換為 p2
Person p3 = (Person) ar.get();
System.out.println("p3 is " + p3); // p3 is id:102
}
}
class Person {
volatile long id;
public Person(long id) { this.id = id; }
public String toString() { return "id:" + id; }
}
注意:Person 未重寫 equals(),默認比較引用地址,故 p3.equals(p1) == false。