问:既然在java中引用的赋值操作本身就是是原子的,那为什么还需要AtomicReference(原子引用)?
答:如果仅需要通过赋值操作改变一个引用,确实不需要AtomicReference。
// 注意volatile关键字
volatile Person person = new person("Jim");
public void processA() {
// 赋值操作是原子的
persion = new persion("Tom");
}
实际上相当于仅使用了AtomicReference的set()方法,看一下set()的实现:
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(V newValue) {
value = newValue;
}
AtomicReference的set()方法,其实就是直接赋值。
真正需要使用AtomicReference的场景是你需要CAS类操作时,由于涉及到比较、设置等多于一个的操作,需要借用Unsafe类的原子操作,比如:
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}