• AtomicInteger


    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);
        }
    }
  • 相关阅读:
    沟通的5个步骤
    安家博客园,发表感想
    postman 简单教程-实现简单的接口测试
    Postman的基本使用
    面试题-如何测试一个APP
    Fiddler快捷方式导出jmeter脚本,傻瓜式
    Servlet学习(三)
    scala学习(一)
    白底抠图
    Servlet学习(二)
  • 原文地址:https://www.cnblogs.com/allenwas3/p/8401360.html
Copyright © 2020-2023  润新知