美文网首页
AtomicInteger-java并发编程(一)

AtomicInteger-java并发编程(一)

作者: 卫渐行 | 来源:发表于2018-09-18 22:20 被阅读85次

    1: AtomicInteger 是通过Unsafe实现在并发情况对于interger的常见操作
    2: AtomicInteger 采取乐观锁CAS
    下面通过对AtomicInteger+unSafe的CAS的源代码分析,进一步了解java并发情况下的编程;主要的方法unsafe的compareAndSwapInt,objectFieldOffset;AtominInteger中volatile修饰的value,以及incrementAndGet的实现原理;

    • unsafe.compareAndSwapInt(this, valueOffset, expect, update)为native方法; this表明该object类,valueOffset;这个参数表明是内存偏移量;expect,内存中的原来的值,update为新值
    • 通过objectFieldOffset找到引用地址为value的object的内存偏移量,通过内存偏移量获取到引用地址对应的内容
    static {
            try {
                valueOffset = unsafe.objectFieldOffset
                    (AtomicInteger.class.getDeclaredField("value"));
            } catch (Exception ex) { throw new Error(ex); }
        }
    
    • 注意成员变量int value ,是被volatile修饰,即每次取值都是内存中的最新值,同时,更新时候也会将最新值更新到内存中
    • 注意AtomicInteger的incrementAndGet方法有个for循环;该循环中通过get()方法获取到最新的内存值,如果有其他线程在更新当前值,不更新该值;如果没有其他线程操作,则更新成功
    public final int incrementAndGet() {
        for (;;) {
    //  获取当前值,因为被volatile修饰,即为当前值(原子操作)
            int current = get();
    //更新当前值;非原子操作
            int next = current + 1;
    //**特别注意:如果current发生变化,即有其他线程更新该值,等待其他线程修改好,然后重新进行运算
            if (compareAndSet(current, next))
                return next;
        }
    }
    

    3: 应用

     public static void main(String[] args) {
    //定义AtomicInteger,
            AtomicInteger atomicInteger = new AtomicInteger(1);
            long tt = System.currentTimeMillis();
    //开启固定大小的线程池
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            for (int k = 0; k < 10; k++) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            atomicInteger.incrementAndGet();
                        } catch (java.lang.Exception e) {
                            System.out.println(e);
                        }
                    }
                });
            }
            executorService.shutdown();
            System.out.println("atmoic : " + atomicInteger);
            System.out.println("time cost: "+ (System.currentTimeMillis()-tt));
        }
    

    参考文献:
    UnSafe的class源码:http://www.docjar.com/html/api/sun/misc/Unsafe.java.html
    java 并发大神 doug-lea http://ifeve.com/doug-lea/
    优秀博客 https://fangjian0423.github.io/2016/03/16/java-AtomicInteger-analysis/

    相关文章

      网友评论

          本文标题:AtomicInteger-java并发编程(一)

          本文链接:https://www.haomeiwen.com/subject/gxbqnftx.html