对CAS中atomicInteger实现的思考

 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问题

 

猜你喜欢

转载自www.cnblogs.com/zhangfengshi/p/9179568.html
今日推荐