【JUC】14-LongAddr源码分析

news2024/9/20 14:45:27

1. LongAddr底层实现过程

在这里插入图片描述

2. Striped64中变量或方法的定义

  • base:类似于AtomicLong中全局的value值。在没有竞争情况下数据直接累加到base上,或者cells扩容时,也需要将数据写入到base上。
  • collide:表示扩容意向,false一定不会扩容,true可能会扩容。
  • cellsBusy:初始化cells或者扩容cells需要获取锁,0表示无锁,1表示其他线程已经持有锁。
  • casCellsBusy():通过CAS操作修改cellsBusy的值,CAS成功获取锁,返回true。
  • getProbe():获取当前线程的hash值。
  • advanceProbe():重置当前线程的hash值。

3. LongAddr设计思想

 LongAddr基本思想是分散热点,将value值分散到一个Cell数组中,不同线程会命中到数组的不同槽中,各个线程只对自己槽中的那个值进行CAS操作,这样热点就被分散了,冲突概率就很小。如果要获取真正的long值,只要将各个槽中的变量值累加返回。
在这里插入图片描述
 LongAdder在无竞争的情况,跟AtomicLong一样,对同一个base进行操作,当出现竞争关系时则是采用化整为零分散热点的做法,用空间换时间,用一个数组cells,将一个value拆分进这个数组cells。多个线程需要同时对value进行操作时候,可以对线程id进行hash得到hash值,再根据hash值映射到这个数组cells的某个下标,再对下标对应的值进行自增操作。当所有线程操作完毕,将数组cells的所有值和base都加起来作为最终结果。
在这里插入图片描述
在这里插入图片描述

4. LongAddr源码分析

更新步骤:

  1. 若Cells为空,尝试CAS更新base字段,成功则退出;
  2. 若Cells为空,CAS更新base字段失败,出现竞争,uncontended为true,调用longAccumulate;
  3. 若Cells非空,但当前线程映射槽为空,uncontended为true,调用longAccumulate;
  4. 若Cells非空,且当前线程映射槽非空,CAS更新Cell的值,成功则返回,否则,uncontended设为false,调用longAccumulate。

longAdder.increment() =>add()=>longAccumulate()

  • add()源码
public void add(long x) {
        // cs表示cells引用
        Cell[] cs;
        // b表示获取的base值, v表示期望值
        long b, v;
        // m表示cells数组的长度
        int m;
        // c表示当前命中的单元格
        Cell c;
		
		// 进入条件为cs不为空或casBase失败 
        if ((cs = cells) != null || !casBase(b = base, b + x)) {
        	// 获取线程id的hash映射
            int index = getProbe();
            // 无竞争。未出现多个线程竞争到一个槽位里面
            boolean uncontended = true;
            // cs未创建或长度为0时候
            if (cs == null || (m = cs.length - 1) < 0 ||
            		// hash值对应的数组为空,需要进行初始化
                    (c = cs[index & m]) == null ||
                    // 对应的单元格cas失败
                    !(uncontended = c.cas(v = c.value, v + x)))
                // 新建或者扩容
                longAccumulate(x, null, uncontended, index);
        }
    }
  • cas比较并交换
    final boolean casBase(long cmp, long val) {
        return BASE.weakCompareAndSetRelease(this, cmp, val);
    }
  • longAccumulate(long x, LongBinaryOperator fn, boolean wasUncontended, int index)
    final void longAccumulate(long x, LongBinaryOperator fn,
                              boolean wasUncontended, int index) {
        if (index == 0) {
            ThreadLocalRandom.current(); // force initialization
            index = getProbe();
            wasUncontended = true;
        }
        for (boolean collide = false;;) {       // True if last slot nonempty
            Cell[] cs; Cell c; int n; long v;
            if ((cs = cells) != null && (n = cs.length) > 0) {
                if ((c = cs[(n - 1) & index]) == null) {
                    if (cellsBusy == 0) {       // Try to attach new Cell
                        Cell r = new Cell(x);   // Optimistically create
                        if (cellsBusy == 0 && casCellsBusy()) {
                            try {               // Recheck under lock
                                Cell[] rs; int m, j;
                                if ((rs = cells) != null &&
                                    (m = rs.length) > 0 &&
                                    rs[j = (m - 1) & index] == null) {
                                    rs[j] = r;
                                    break;
                                }
                            } finally {
                                cellsBusy = 0;
                            }
                            continue;           // Slot is now non-empty
                        }
                    }
                    collide = false;
                }
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Continue after rehash
                else if (c.cas(v = c.value,
                               (fn == null) ? v + x : fn.applyAsLong(v, x)))
                    break;
                else if (n >= NCPU || cells != cs)
                    collide = false;            // At max size or stale
                else if (!collide)
                    collide = true;
                else if (cellsBusy == 0 && casCellsBusy()) {
                    try {
                        if (cells == cs)        // Expand table unless stale
                            cells = Arrays.copyOf(cs, n << 1);
                    } finally {
                        cellsBusy = 0;
                    }
                    collide = false;
                    continue;                   // Retry with expanded table
                }
                index = advanceProbe(index);
            }
            else if (cellsBusy == 0 && cells == cs && casCellsBusy()) {
                try {                           // Initialize table
                    if (cells == cs) {
                        Cell[] rs = new Cell[2];
                        rs[index & 1] = new Cell(x);
                        cells = rs;
                        break;
                    }
                } finally {
                    cellsBusy = 0;
                }
            }
            // Fall back on using base
            else if (casBase(v = base,
                             (fn == null) ? v + x : fn.applyAsLong(v, x)))
                break;
        }
    }

5. longAccumulate

// x为默认值, fn默认null, wasUncontended为false代表竞争失败了
final void longAccumulate(long x, LongBinaryOperator fn,
                              boolean wasUncontended, int index) {
        // 强制获取hash值
        if (index == 0) {
            ThreadLocalRandom.current(); // force initialization
            index = getProbe();
            wasUncontended = true;
        }
        for (boolean collide = false;;) {       // True if last slot nonempty
            Cell[] cs; Cell c; int n; long v;
            // cells已经被初始化了
            if ((cs = cells) != null && (n = cs.length) > 0) {
                if ((c = cs[(n - 1) & index]) == null) {
                    // double check
                    if (cellsBusy == 0) {       // Try to attach new Cell
                        Cell r = new Cell(x);   // Optimistically create
                        if (cellsBusy == 0 && casCellsBusy()) {
                            try {               // Recheck under lock
                                Cell[] rs; int m, j;
                                if ((rs = cells) != null &&
                                    (m = rs.length) > 0 &&
                                    rs[j = (m - 1) & index] == null) {
                                    rs[j] = r;
                                    break;
                                }
                            } finally {
                                cellsBusy = 0;
                            }
                            continue;           // Slot is now non-empty
                        }
                    }
                    collide = false;
                }
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Continue after rehash
                else if (c.cas(v = c.value,
                               (fn == null) ? v + x : fn.applyAsLong(v, x)))
                    break;
                else if (n >= NCPU || cells != cs)
                    collide = false;            // At max size or stale
                else if (!collide)
                    collide = true;
                else if (cellsBusy == 0 && casCellsBusy()) {
                    try {
                        if (cells == cs)        // Expand table unless stale
                            cells = Arrays.copyOf(cs, n << 1);
                    } finally {
                        cellsBusy = 0;
                    }
                    collide = false;
                    continue;                   // Retry with expanded table
                }
                index = advanceProbe(index);
            }
            // cells没有加锁且没有初始化,则尝试对它进行加锁,并初始化cells数组
            else if (cellsBusy == 0 && cells == cs && casCellsBusy()) {
                try {                           // Initialize table
                    if (cells == cs) {
                    	// 新建长度为2的数组
                        Cell[] rs = new Cell[2];
                        // 将值映射到cells中
                        rs[index & 1] = new Cell(x);
                        cells = rs;
                        break;
                    }
                } finally {
                    cellsBusy = 0;
                }
            }
            // Fall back on using base,cells正在进行初始化,则尝试直接在base上进行累加操作
            else if (casBase(v = base,
                             (fn == null) ? v + x : fn.applyAsLong(v, x)))
                break;
        }
    }

在这里插入图片描述

6. LongAddr在并发情况下sum的值不精确

sum执行时,并没有限制对base和cells的更新。所以LongAddr不是强一致性的,它是最终一致性。

    public long sum() {
        Cell[] cs = cells;
        long sum = base;
        if (cs != null) {
            for (Cell c : cs)
                if (c != null)
                    sum += c.value;
        }
        return sum;
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2123852.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

反转链表 II

题目 给你单链表的头指针 head 和两个整数 left 和 right &#xff0c;其中 left < right 。请你反转从位置 left 到位置 right 的链表节点&#xff0c;返回 反转后的链表 。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5], left 2, right 4 输出&#xff1a;…

Java中的ArrayList类

继承实现关系 Arraylist就是一个可以动态扩容的容器&#xff0c;属于集合类的一种&#xff0c;要追根溯源的话它是间接实现了Collection接口&#xff0c;下面我画一下它的结构图 类定义 ArrayList类继承自抽象类AbstractList&#xff0c;同时实现了List和Collection接口&…

服务器数据恢复—通过拼接数据库碎片的方式恢复SQL Server数据库数据

服务器数据恢复环境&#xff1a; 一台服务器中有一组由4块STAT硬盘通过RAID卡组建的RAID10阵列&#xff0c;上层是XenServer虚拟化平台&#xff0c;虚拟机安装Windows Server操作系统&#xff0c;作为Web服务器使用。 服务器故障&#xff1a; 因机房异常断电导致服务器中一台V…

元学习之应用案例

现在在做元学习的时候&#xff0c;我们最常拿来测 试元学习技术的任务叫做少样本图像分类&#xff0c;简单来讲就是每一个任务都只有几张图片&#xff0c;每一 个类别只有几张图片。比如我们使用图1的案例为例说明。现在分类的任务是分为三个 类别&#xff0c;每个类别都只有两…

贪心-用最少的箭射球

一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭&#xff0c;若有一个气球的直径的开始和结束坐标为 xstart&#xff0c;xend&#xff0c; 且满足 xstart ≤ x ≤ xend&#xff0c;则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后…

MySQL从C盘迁移到D盘

文章目录 前言一、停止MySQL服务打开服务&#xff08;方式一&#xff09;打开服务&#xff08;方式二&#xff09;停止MySQL服务 二、找到C盘中的文件文件夹1文件夹2文件夹3 三、修改文件内容1.对应文件夹12.对应文件夹3 四、 修改注册表中文件路径1.打开注册表2. 修改注册表中…

微积分-积分应用5.5(函数的平均值)

很容易计算有限多个数字 y 1 , y 2 , … , y n y_1, y_2, \dots, y_n y1​,y2​,…,yn​ 的平均值&#xff1a; y ave y 1 y 2 ⋯ y n n y_{\text{ave}} \frac{y_1 y_2 \cdots y_n}{n} yave​ny1​y2​⋯yn​​ 但是&#xff0c;如果可以进行无限多次的温度读取&…

Java 入门指南:Java 并发编程 —— 同步工具类 CountDownLatch(倒计时门闩)

文章目录 同步工具类CountDownLatch常用方法使用步骤适用场景使用示例 同步工具类 JUC&#xff08;Java.util.concurrent&#xff09;是 Java 提供的用于并发编程的工具类库&#xff0c;其中包含了一些通信工具类&#xff0c;用于在多个线程之间进行协调和通信&#xff0c;特别…

【kafka】kafka如何保证数据的可靠性,kafka如何保证数据不丢失

1. Kafka架构&#xff1a; Producer - Broker - Consumer 回到问题上来&#xff0c;Kafka如何保证数据不丢失&#xff0c;我们先看看Kafka如何保证Producer端数据不丢失&#xff1a; 通过ack机制 最小副本数设置 生产者重试机制 2. Kafka Producer消息发送ACK机制&#xff1…

量化交易backtrader实践(一)_数据获取篇(2)_tushare与akshare

上一节回顾 在上一节中&#xff0c;从股票的基本功能和主要数据进行小结&#xff0c;明确了进行backtrader回测所需要的数据&#xff0c;并且学习了backtrader的数据来源以及PandasData的格式要求&#xff0c;已经做到假设拿到.txt或.csv文件后&#xff0c;能把里面的股票基本…

【代码随想录】字符串

本博文为《代码随想录》学习笔记&#xff0c;原文链接&#xff1a;代码随想录 344.反转字符串 题目链接&#xff1a;. - 力扣&#xff08;LeetCode&#xff09; 编写一个函数&#xff0c;其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。 不要给另外的…

Qt使用绿色pdf阅读器打开文件

1.下载SumatraPDF 2.设置 3.代码 void MainWindow::on_pushButton_clicked() {QProcess *process new QProcess();QString filePath "C:\\Users\\jude\\Desktop\\su\\11.pdf";QString sumatraPath "C:\\Users\\jude\\Desktop\\su\\SumatraPDF-3.5.2-64.exe&q…

Android 系统级应用守护进程

import java.util.Random; /** Application class for SystemUI. -42,6 69,8 public class SystemUIApplication extends Application { private static final String TAG “SystemUIService”; private static final boolean DEBUG false; private Context mContext;/*…

嵌入式产品发货后出现问题,怎么办?

目录 1、问题识别与初步诊断 2、影响评估 3、提出临时解决方案 4、根本原因分析与修复 5、修复验证与回归测试 6、修复的部署与客户沟通 7、预防未来类似问题 当嵌入式电子产品已发货且出现问题时&#xff0c;及时采取有效的补救措施是至关重要的。补救步骤应包括问题的…

javascript柯里化

return a b c d; } //通常调用方式 var sum add(1, 2, 3, 4); //柯里化的调用方式 var curryAdd Curry(add); var sum curryAdd(1)(2)(3)(4); //或者很多奇怪的方式调用 var sum curryAdd(1, 2)(3, 4); var sum curryAdd(1, 2, 3)(4); var sum curryAdd(1)(…

C语言 | Leetcode C语言题解之第398题随机数索引

题目&#xff1a; 题解&#xff1a; typedef struct {int *nums;int numsSize; } Solution;Solution* solutionCreate(int* nums, int numsSize) {Solution *obj (Solution *)malloc(sizeof(Solution));obj->nums nums;obj->numsSize numsSize;return obj; }int solu…

Maven之坑setting.xml配置

先来看遇到的问题 在运行 mvn clean package 打包命令的时候&#xff0c;IDEA控制台提示如下 Non-resolvable parent POM for com.xxxxx.xxxxx:1.0.0: The following artifacts could not be resolved: com.xxxxx:xxxxx:pom:1.0.0 (present, but unavailable): xxxxx:xxxxx…

全球热门剪辑软件大搜罗

如果你要为你的视频进行配音那肯定离不开音频剪辑软件&#xff0c;现在有不少音频剪辑软件免费版本就可以实现我们并不复杂的音频剪辑操作。这次我就给你分享几款能提高剪辑效率的音频剪辑工具。 1.福晰音频剪辑 链接直达>>https://www.foxitsoftware.cn/audio-clip/ …

Java面试篇基础部分-Java各种垃圾收集器

导语   在之前的分享中,我们知道Java堆内存被分为新生代和老年代两个部分;其中,新生代中主要存储生命周期较短的对象,了解了新生代中的对象采用的是复制算法进行垃圾回收;而老年代主要存储生命周期较长的对象以及大对象,采用的是标记整理算法进行垃圾回收。 针对不同的…

Es6解构赋值,熟练掌握作用域

5.3 数组的解构赋值 数组的解构赋值是按照前后数据的索引值一一对应的 5.4 前后数据结构也要保持一致,不然解构的可能与原数组解构嵌套不同 5.5 数组解构时的默认值 6 对象的解构赋值 对象的解构赋值是按照key一一解构 7 解构数组,如果有两个值必须写在后面,rest参数 8 解…