V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lihahahayang
V2EX  ›  Java

ConcurrentHashMap 源码中 initTable()方法疑问

  •  
  •   lihahahayang · 2022-01-12 17:28:55 +08:00 · 1682 次点击
    这是一个创建于 832 天前的主题,其中的信息可能已经有所发展或是发生改变。

    ConcurrentHashMap 源码中 initTable()方法为啥要使用临时变量 tab 和 sc ,集合中变量 table 不都是已经 volatile 立即可见的吗,每次都要拷贝到临时变量中有啥具体意义吗? 这样写不行吗? while (table == null || table.length == 0)

    /**

    • Initializes table, using the size recorded in sizeCtl. */ private final Node<K,V>[] initTable() { Node<K,V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { // 如果 sizeCtl < 0 ,说明另外的线程执行 CAS 成功,正在进行初始化。 if ((sc = sizeCtl) < 0) // 让出 CPU 使用权 Thread.yield(); // lost initialization race; just spin else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; @SuppressWarnings("unchecked") Node<K,V>[] nt = (Node<K,V>[])new Node[n]; table = tab = nt; sc = n - (n >>> 2); } } finally { sizeCtl = sc; } break; } } return tab; }
    3 条回复    2022-01-19 10:01:46 +08:00
    lihahahayang
        1
    lihahahayang  
    OP
       2022-01-12 17:33:33 +08:00
    自己又看了看,方法中进行拷贝主要减少 table 变量的竞争,数据更新都是通过对 table 的 cas 操作完成。
    huang119412
        3
    huang119412  
       2022-01-19 10:01:46 +08:00
    It's a coding style made popular by Doug Lea. It's an extreme optimization that probably isn't necessary;
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5315 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 09:00 · PVG 17:00 · LAX 02:00 · JFK 05:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.