Atomicreference Introduction and Functions List
Atomicreference is a function of atomic manipulation of "objects".
atomicreference Function List
// Create a new AtomicReference with null initial value.
AtomicReference ()
// Create a new AtomicReference with the given initial value.
AtomicReference (V initialValue)
// If the current value == the expected value, then atomically set the value to the given update value.
boolean compareAndSet (V expect, V update)
// Get the current value.
V get ()
// Set to the given value atomically and return the old value.
V getAndSet (V newValue)
// Finally set to the given value.
void lazySet (V newValue)
// Set to the given value.
void set (V newValue)
// Return the string representation of the current value.
String toString ()
// If the current value == the expected value, then atomically set the value to the given update value.
boolean weakCompareAndSet (V expect, V update)
AtomicReference source code analysis (based on JDK1.7.0_40)
The source code of AtomicReference.java in JDK1.7.0_40 is as follows:
public class AtomicReference <V> implements java.io.Serializable {
private static final long serialVersionUID = -1848883965231344442L;
// Get Unsafe object, the role of Unsafe is to provide CAS operation
private static final Unsafe unsafe = Unsafe.getUnsafe ();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicReference.class.getDeclaredField ("value"));
} catch (Exception ex) {throw new Error (ex);}
}
// volatile type
private volatile V value;
public AtomicReference (V initialValue) {
value = initialValue;
}
public AtomicReference () {
}
public final V get () {
return value;
}
public final void set (V newValue) {
value = newValue;
}
public final void lazySet (V newValue) {
unsafe.putOrderedObject (this, valueOffset, newValue);
}
public final boolean compareAndSet (V expect, V update) {
return unsafe.compareAndSwapObject (this, valueOffset, expect, update);
}
public final boolean weakCompareAndSet (V expect, V update) {
return unsafe.compareAndSwapObject (this, valueOffset, expect, update);
}
public final V getAndSet (V newValue) {
while (true) {
V x = get ();
if (compareAndSet (x, newValue))
return x;
}
}
public String toString () {
return String.valueOf (get ());
}
}