What Unsafe and CAS are

Today interview was asked CAS principle, my answer is

It will use an incremental version numbers to determine whether the data had changed when the data do change, if change has occurred to spin until the latest value and change;

There are two places I have been misunderstood:

1. The version number is incremented, so I did not understand why the CAS will lead the ABA problem

2.CAS will spin until the latest value do update, then actually call Unsafe AtomicInteger do things (although there are source've seen before, but the idea is erroneous preconceptions)

// 代码1:AtomicInteger add方法
public final int getAndAdd(int delta) {
    return unsafe.getAndAddInt(this, valueOffset, delta);
}
// Code 2: add the corresponding method Unsafe 
public  Final  int getAndAddInt (Object var1, Long var2, int var4) {
     int var5;
     do {
        var5 = this.getIntVolatile(var1, var2);
    } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
    return var5;
}
// 代码3:AtomicInteger set方法
public final int getAndSet(int newValue) {
    return unsafe.getAndSetInt(this, valueOffset, newValue);
}
// Code 4: set a corresponding method Unsafe 
public  Final  int getAndAddInt (Object var1, Long var2, int var4) {
     int var5;
     do {
        var5 = the this .getIntVolatile (var1, var2);
         // this.compareAndSwapInt (var1, var2, var5, var5 + var4)
         // var1 AtomicInteger represents the current instance of the object
         // var2 memory offset, understood as a simple memory address of var1 , the code assignment is AtomicInteger static code block specific see the code 5
         // var5 expected old value
         // var5 + new value after var4 successfully changed 
    } the while (! the this .compareAndSwapInt (var1, var2, var5, var5 + var4));
     return var5;
}
// 代码5:Integer
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); }
}

 

Guess you like

Origin www.cnblogs.com/zjack/p/11079950.html