AtomicInteger类的使用

AtomicInteger介绍

AtomicInteger是一个提供原子操做的Integer类,经过线程安全的方式操做加减。java

AtomicInteger使用场景

AtomicInteger提供原子操做来进行Integer的使用,所以十分适合高并发状况下的使用。算法

AtomicInteger源码部分讲解

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

    // setup to use Unsafe.compareAndSwapInt for updates
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicInteger.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile int value;

这里, unsafe是java提供的得到对对象内存地址访问的类,注释已经清楚的写出了,它的做用就是在更新操做时提供“比较并替换”的做用。实际上就是AtomicInteger中的一个工具。安全

valueOffset是用来记录value自己在内存的编译地址的,这个记录,也主要是为了在更新操做在内存中找到value的位置,方便比较。并发

注意:value是用来存储整数的时间变量,这里被声明为volatile,就是为了保证在更新操做时,当前线程能够拿到value最新的值(并发环境下,value可能已经被其余线程更新了)。高并发

这里,咱们以自增的代码为例,能够看到这个并发控制的核心算法:工具

/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
//这里能够拿到value的最新值
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}

public final boolean compareAndSet(int expect, int update) {
//使用unsafe的native方法,实现高效的硬件级别CAS
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
相关文章
相关标签/搜索