类图:
源码:
package java.util.concurrent.atomic;
import java.util.function.UnaryOperator;
import java.util.function.BinaryOperator;
import sun.misc.Unsafe;
//原子变量类 V:变量类型
public class AtomicReference<V> implements java.io.Serializable {
private static final long serialVersionUID = -1848883965231344442L;//版本号
private static final Unsafe unsafe = Unsafe.getUnsafe();//使用sun的Unsafe完成cas指令
private static final long valueOffset;//value内存地址相对于对象内存地址的偏移量
private volatile V value;//变量类型
static {
try {
//初始化valueOffset:通过unsafe.objectFieldOffset方法获取成员属性value内存地址相对于对象内存地址的偏移量
valueOffset = unsafe.objectFieldOffset (AtomicReference.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
//构造方法:value为null
public AtomicReference() {
}
/**
* 构造方法,传入指定V值
*/
public AtomicReference(V initialValue) {
value = initialValue;
}
/**
* 获取v值
*/
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);
}
/**
* CAS操作,现代CPU已广泛支持,是一种原子操作;
* 简单地说,当期待值expect与valueOffset地址处的值相等时,设置为update值
*/
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
//和compareAndSet()方法相同
public final boolean weakCompareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
//以原子方式设置为给定值,并返回旧值
public final V getAndSet(V newValue) {
return (V)unsafe.getAndSetObject(this, valueOffset, newValue);
}
/**
* 以原子方式设置为给定值,并返回旧值
* updateFunction 一个参数的函数
*/
public final V getAndUpdate(UnaryOperator<V> updateFunction) {
V prev, next;
do {
prev = get();
next = updateFunction.apply(prev);
} while (!compareAndSet(prev, next));
return prev;
}
/**
* 以原子方式设置为给定值,并返回新值
* updateFunction 一个参数的函数
*/
public final V updateAndGet(UnaryOperator<V> updateFunction) {
V prev, next;
do {
prev = get();
next = updateFunction.apply(prev);
} while (!compareAndSet(prev, next));
return next;
}
/**
* 以原子方式设置为给定值,并返回旧值
* accumulatorFunction 两个参数的函数
*/
public final V getAndAccumulate(V x, BinaryOperator<V> accumulatorFunction) {
V prev, next;
do {
prev = get();
next = accumulatorFunction.apply(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}
/**
* 以原子方式设置为给定值,并返回新值
* accumulatorFunction 两个参数的函数
*/
public final V accumulateAndGet(V x,BinaryOperator<V> accumulatorFunction) {
V prev, next;
do {
prev = get();
next = accumulatorFunction.apply(prev, x);
} while (!compareAndSet(prev, next));
return next;
}
//返回v类的toString()方法得到的字符串
public String toString() {
return String.valueOf(get());
}
}