//保存atomiclong的实际值,用volatile 修饰保证可见性
private volatile long value;
// 获取value的内存地址的逻辑操作
static {
try {
valueoffset = unsafe.objectfieldoffset
(atomiclong.class.getdeclaredfield("value"));
} catch (exception ex) { throw new error(ex); }
}
//根据传入的参数初始化实际值,默认值为0
public atomiclong(long initialvalue) {
value = initialvalue;
}
接下来我们主要看一下几个更新方法
//以原子方式更新值为传入的newvalue,并返回更新之前的值
public final long getandset(long newvalue) {
return unsafe.getandsetlong(this, valueoffset, newvalue);
}
//输入期望值和更新值,如果输入的值等于预期值,则以原子方式更新该值为输入的值
public final boolean compareandset(long expect, long update) {
return unsafe.compareandswaplong(this, valueoffset, expect, update);
}
//返回当前值原子加1后的值
public final long getandincrement() {
return unsafe.getandaddlong(this, valueoffset, 1l);
}
//返回当前值原子减1后的值
public final long getanddecrement() {
return unsafe.getandaddlong(this, valueoffset, -1l);
}
//返回当前值原子增加delta后的值
public final long getandadd(long delta) {
return unsafe.getandaddlong(this, valueoffset, delta);
}
public native long getlongvolatile(object var1, long var2);
public final native boolean compareandswaplong(object var1, long var2, long var4, long var6);
/*
unsafe.getandaddlong(this, valueoffset, 1l)
var1 当前值
var2 value值在atomiclong对象中的内存偏移地址
*/
public final long getandaddlong(object var1, long var2, long var4) {
long var6;
do {
//根据var1和var2得出当前变量的值,以便接下来执行更新操作
var6 = this.getlongvolatile(var1, var2);
//如果当前值为var6,则将值加var4,这样做是确保每次更新时,变量的值是没有被其他线
//程修改过的值,如果被修改,则重新获取最新值更新,直到更新成功
} while(!this.compareandswaplong(var1, var2, var6, var6 + var4));
return var6;
}