AutoInteger中的incrementAndGet 和 getAndIncrement
/**
* Atomically increments by one the current value.
*
* @return the updated value 返回更新的值
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
/**
* Atomically increments by one the current value.
*
* @return the previous value 返回先前的旧值
*/
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
// java8
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
//java8
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
由此可以看出,两个方法处理的方式都是一样的,区别在于
getAndIncrement
方法是返回旧值(即加1前的原始值),而
incrementAndGet
返回的是新值(即加1后的值)
可以看出java8在源码层面使用的是同一个方法