原子类AtomicInteger在多线程场景下用处很多,AtomicInteger是在使用非阻塞算法实现并发控制,在一些高并发程序中非常适合,但并不能每一种场景都适合,不同场景要使用使用不同的数值类。来看下这个类
构造函数
// 给定初始值
public AtomicInteger(int initialValue) {
value = initialValue;
}
// 无参构造
public AtomicInteger() {
}
注意到静态代码块
static {
try {
// 初始是0
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
AtomicInteger类属性
// setup to use Unsafe.compareAndSwapInt for updates
// 使用Unsafe类做地层数据的更新
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
// 此值被volatile修饰,确保内存可见性
private volatile int value;
常用api
// Gets the current value.
public final int get() {
return value;
}
// Sets to the given value.
public final void set(int newValue) {
value = newValue;
}
// Atomically sets to the given value and returns the old value.
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
// Atomically sets the value to the given updated value
// if the current value == the expected value.
public final boolean compareAndSet(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() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, valueOffset, -1);
}
/**
* 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) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
/**
* 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) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}