并发:AtomicInteger 源码

2018-12-03  本文已影响7人  Kate_Blog

Java中的AtomicInteger大家应该很熟悉,它是为了解决多线程访问Integer变量导致结果不正确所设计的一个基于多线程并且支持原子操作的Integer类。

它的使用也非常简单:
AtomicInteger ai = new AtomicInteger(0);
ai.addAndGet(5); // 5
ai.getAndAdd(1); // 5
ai.get(); // 6
AtomicInteger内部有一个变量UnSafe:
private static final Unsafe unsafe = Unsafe.getUnsafe();

Unsafe中的int类型的CAS操作方法:

public final native boolean compareAndSwapInt(Object o, long offset,
                                                int expected,
                                                int x);
compareAndSwapInt(this, valueOffset, 1, 2)
static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicInteger.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
public final int addAndGet(int delta) {
    for (;;) {
        int current = get();
        int next = current + delta;
        if (compareAndSet(current, next))
            return next;
    }
}
public final int incrementAndGet() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return next;
    }
}
public final int getAndAdd(int delta) {
    for (;;) {
        int current = get();
        int next = current + delta;
        if (compareAndSet(current, next))
            return current;
    }
}

缺点:

虽然AtomicInteger中的cas操作可以实现非阻塞的原子操作,但是会产生ABA问题,

上一篇 下一篇

猜你喜欢

热点阅读