AtomicLong AtomicDouble AtomicInteger

Atomic+数字类型 大多都持有一个静态的Unsafe对象,通过unsafe 对属性在类对象的offset cas直接操作物理内存实现对数据的修改

public class AtomicLong extends Number implements java.io.Serializable {
private static final long serialVersionUID = 1927816293512124184L;

// setup to use Unsafe.compareAndSwapLong for updates
private static final Unsafe unsafe = Unsafe.getUnsafe(); //Unsafe是单例的
private static final long valueOffset;

/**
* Records whether the underlying JVM supports lockless
* compareAndSwap for longs. While the Unsafe.compareAndSwapLong
* method works in either case, some constructions should be
* handled at Java level to avoid locking user-visible locks.
*/
static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8();

public final boolean compareAndSet(long expect, long update) {
return unsafe.compareAndSwapLong(this, valueOffset, expect, update);
}



public final boolean weakCompareAndSet(long expect, long update) {
return unsafe.compareAndSwapLong(this, valueOffset, expect, update);
}



public final long getAndIncrement() {
return unsafe.getAndAddLong(this, valueOffset, 1L);
}

/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final long getAndDecrement() {
return unsafe.getAndAddLong(this, valueOffset, -1L);
}

''''''''''''
}
posted @ 2020-05-22 10:25  清明雨下  阅读(648)  评论(0)    收藏  举报