public class AtomicInteger extends Number implements java.io.Serializable {
    // setup to use Unsafe.compareAndSwapInt for updates
    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); }
    }
    
    //使用volatile修饰,保证每次都是从主存中读取
    private volatile int value;
    
    public final int get() {
        return value;
    }
    public final void set(int newValue) {
        value = newValue;
    }
    
    //get旧值,set新值。 
    //CAS操作本来是不阻塞的,但是这里是死循环,只有当CAS返回true时,才会出循环。
    public final int getAndSet(int newValue) {
        for (;;) {
            //每次循环,都是重新get值
            int current = get();
            if (compareAndSet(current, newValue))
                return current;
        }
    }
    
    //CAS本人,都说它是原子操作,在汇编里是一条指令。
    //首先拿到旧值,如果旧值和内存相等,并修改成功,则返回true。
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }
}

 

posted on 2018-02-01 21:25  偶尔发呆  阅读(175)  评论(0编辑  收藏  举报