设为首页 加入收藏

TOP

Java高并发之无锁与Atomic源码分析(九)
2018-06-09 10:07:57 】 浏览:1271
Tags:Java 并发 Atomic 源码 分析
nbsp;       int pos = desc.size + FIRST_BUCKET_SIZE;
            // 取出pos 的前导0
            int zeroNumPos = Integer.numberOfLeadingZeros(pos);
            // zeroNumFirst  为FIRST_BUCKET_SIZE 的前导0
            // bucketInd 数据应该放到哪一个一维数组(篮子)里的
            int bucketInd = zeroNumFirst - zeroNumPos;
            // 00000000 00000000 00000000 00001000 第一个篮子满 8
            // 00000000 00000000 00000000 00011000 第二个篮子满 8 + 16
            // 00000000 00000000 00000000 00111000 第三个篮子满 8 + 16 + 32
            // ... bucketInd其实通过前导0相减, 就是为了得出来当前第几个篮子是空的.


            // 判断这个一维数组是否已经启用, 可能是第一次初始化
            if (buckets.get(bucketInd) == null) {
                //newLen  一维数组的长度, 取前一个数组长度 * 2
                int newLen = 2 * buckets.get(bucketInd - 1).length();
                // 设置失败也没关系, 只要有人初始化成功就行
                buckets.compareAndSet(bucketInd, null,
                        new AtomicReferenceArray<E>(newLen));
            }


            // 在这个一位数组中,我在哪个位置
            // 0x80000000是 10000000 00000000 00000000 00000000
            // 这句话就是把上述111000, 第一个1变成了0, 得到011000, 即新值的位置.
            int idx = (0x80000000>>>zeroNumPos) ^ pos;
            // 通过bucketInd与idx来确定元素在二维数组中的位置
            // 期望写入的时候, 该位置值是null, 如果非null, 说明其他线程已经写了, 则继续循环.
            newd = new Descriptor<E>(desc.size + 1, new WriteDescriptor<E>(
                    buckets.get(bucketInd), idx, null, e));
            // 循环cas设值
        } while (!descriptor.compareAndSet(desc, newd));
        descriptor.get().completeWrite();
    }


    /**
    * Remove the last element in the vector.
    *
    * @return element removed
    */
    public E pop_back() {
        Descriptor<E> desc;
        Descriptor<E> newd;
        E elem;
        do {
            desc = descriptor.get();
            desc.completeWrite();


            int pos = desc.size + FIRST_BUCKET_SIZE - 1;
            int bucketInd = Integer.numberOfLeadingZeros(FIRST_BUCKET_SIZE)
                    - Integer.numberOfLeadingZeros(pos);
            int idx = Integer.highestOneBit(pos) ^ pos;
            elem = buckets.get(bucketInd).get(idx);
  &nb

首页 上一页 6 7 8 9 10 下一页 尾页 9/10/10
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇JDK并发包详细总结 下一篇Java内存模型与指令重排

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目