对CAS中atomicInteger实现的思考

CAS是unSafe类中compareAndSwapInt,compareAndSwapLong等几个方法包装提供

 

 public final int incrementAndGet() {

        for (;;) {

            int current = get();

            int next = current + 1;

            if (compareAndSet(current, next))

                return next;

        }

    }

public final boolean compareAndSet(int expect, int update) {

        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);

    }

原来对它的原理一直不大理解 

 

通过注释解读反而很清楚了

 

原来它是通过比较value和上文中的所谓的期望值current进行最终比较  如果相等  认为没被篡改过

但其实还是会有ABA问题

 

就是

 

posted @ 2018-06-13 20:02  陶朱公Boy  阅读(228)  评论(0编辑  收藏  举报