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

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

 

就是

 

相关文章:

  • 2022-03-05
  • 2021-09-02
  • 2021-05-26
  • 2021-11-10
  • 2021-06-26
  • 2021-04-05
  • 2021-07-29
猜你喜欢
  • 2021-12-28
  • 2021-06-01
  • 2022-12-23
  • 2021-12-23
  • 2022-12-23
相关资源
相似解决方案