接着前两篇的AtomicBoolean和AtomicInteger再来看看AtomicReference类上的注释说明:
An object refenrence that may be updated atomically.用来原子更新对象的引用。
一、AtomicRefenrence属性
private static final Unsafe unsafe = Unsafe.getUnsafe();private static final long valueOffset;private volatile V value;
static{ try{ valueOffset = unsafe.objectFieldOffset (AtomicReference.class.getDeclaredField("value")); }catch(Exception e){ throw new Error(ex); }}
二、构造器
/***Creates a new AtomicReference with the given initial value*/public AtomicReference(V initialValue){ value = initialValue;}/*** Creates a new AtomicReference with null initail value*/public AtomicReference(){}
除了上面的属性、构造器外,AtomicReference与AtomicBoolean、
AtomicInteger在方法上都差不多,这里只提一个方法:
/***Atomically sets to the given value and returns the old value.*/public final V getAndSet(V newValue){ return(V)unsafe.getAndSetObject(this,valueOffset,newValue);}
这个方法同AtomicInteger一样是在Unsafe类里进行自旋,与AtomicBoolean略有不同。