Aomic包下有四种数据类型:AomicBoolean, AomicInteger, AomicLong和AomicReferrence(针对Object的)以及它们的数组类型, 和相对应的AtomicXXXFieldUpdater.
各种数据类型中所有的原子操作都依赖于sun.misc.Unsafe这个类和CAS操作.
sun.misc.Unsafe
Java是一个安全的开发工具, 大部分的底层操作全部封装在JNI中, 阻止开发人员犯很多低级的错误. 但是jdk依然提供了Unsafe类, 用于操作内存. 事实上, jdk是禁止直接构建Unsafe实例的, Unsafe.getUnsafe()只允许被JDK信任的类调用, 如果直接调用会抛出SecutiryException.(进一步了解https://dzone.com/articles/understanding-sunmiscunsafe.)
CAS
现代主流CPU都支持的一种硬件级别的原子操作, 比较并交换, 操作包含三个操作数:
内存位置(V)
预期原值(A)
新值(B)
如果内存位置的值与预期原值相匹配, 那么处理器会自动将该位置值更新为新值,否则, 处理器不做任何操作.无论哪种情况, 它都会在 CAS 指令之前返回该位置的值.
优点: 效率高, 无锁
AtomicXXXX四种数值类型
- value成员都是volatile:
保证写volatile变量会强制把CPU写缓存区的数据刷新到内存;
读volatile变量时,使缓存失效,强制从内存中读取最新的值. - 基本方法get/set
- 主要方法:
compareAndSet,
weakCompareAndSet,
lazySet,
getAndSet: 取当前值, 使用当前值和准备更新的值做CAS. - 对于Long和Integer
getAndIncrement/incrementAndGet,
getAndDecrement/decrementAndGet,
getAndAdd/addAndGet.
三组方法都和getAndSet,取当前值,加减之得到准备更新的值,再做CAS,/左右的区别在于返回的是当前值还是更新值.
以AtomicInteger为例详细说明
1.成员变量
// setup to use Unsafe.compareAndSwapInt for updates
//如前所述, 用于直接操作内存的类
private static final Unsafe unsafe = Unsafe.getUnsafe();
//内存中,成员变量的地址相对于对象的偏移量
private static final long valueOffset;
//利用unsafe计算偏移量valueOffset
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
//存储int值
//volatile保证了新值能立即同步到主内存,以及每次使用前立即从主内存刷新.
//当把变量声明为volatile类型后,编译器与运行时都会注意到这个变量是共享的.
private volatile int value;
2.构造函数
/**
* Creates a new AtomicInteger with the given initial value.
* @param initialValue the initial value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
public AtomicInteger() {
}
3.get/set
/**
* Gets the current value.
* @return the current value
*/
public final int get() {
return value;
}
/**
* Sets to the given value.
* @param newValue the new value
*/
public final void set(int newValue) {
value = newValue;
}
4.主要方法
/**
* Eventually sets to the given value.
* @param newValue the new value
* @since 1.6
*/
//putOrderedXXX方法是putXXXVolatile方法的延迟实现,不保证值的改变被其他线程立即看到.
//volatile变量的修改可以立刻让所有的线程可见,lazySet说白了就是以普通变量的方式来写变量
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final int getAndSet(int newValue) {
for (;;) {
int current = get();
if (compareAndSet(current, newValue))
return current;
}
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final int getAndAdd(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final int addAndGet(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return next;
}
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value.
*/
public String toString() {
return Integer.toString(get());
}
public int intValue() {
return get();
}
public long longValue() {
return (long)get();
}
public float floatValue() {
return (float)get();
}
public double doubleValue() {
return (double)get();
}
网友评论