CAS - 图1

CAS 底层实现

AtomicInteger 为例

  • 利用 unsafe 工具拿到 value 的内存地址
  • 并且利用 volatile 保证 value 的可见性 ```java 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 long value;

  1. ```java
  2. public final int getAndIncrement() {
  3. return unsafe.getAndAddInt(this, valueOffset, 1);
  4. }

Unsafe

  • 这里的 getAndAddInt 就是 do while + cms

    1. // class Unsafe
    2. public final int getAndAddInt(Object var1, long var2, int var4) {
    3. int var5;
    4. do {
    5. var5 = this.getIntVolatile(var1, var2);
    6. } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
    7. return var5;
    8. }
  • cms 是 native 方法,由 os 保证原子性

    1. public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);