V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
esolve
V2EX  ›  问与答

concurrenthashmap 里 getFirst 函数里的一个问题

  •  
  •   esolve · 2017-03-27 15:57:51 +08:00 · 951 次点击
    这是一个创建于 2580 天前的主题,其中的信息可能已经有所发展或是发生改变。

    HashEntry<K,V> More ...getFirst(int hash) { HashEntry<K,V>[] tab = table; return tab[hash & (tab.length - 1)]; }

    这里为何要新建一个 tab 变量? 直接

    return table[hash & (table.length - 1)]; 有啥问题?

    2 条回复    2017-03-28 01:29:55 +08:00
    esolve
        1
    esolve  
    OP
       2017-03-27 16:19:18 +08:00
    HashEntry<K,V> More ...getFirst(int hash) {
    HashEntry<K,V>[] tab = table;
    return tab[hash & (tab.length - 1)];
    }
    SoloCompany
        2
    SoloCompany  
       2017-03-28 01:29:55 +08:00
    因为这是设计给无锁并发线程安全场景的,如果不先赋值给局部变量,两次对 table 的访问可能返回两个不一样的实例
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1144 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 18:21 · PVG 02:21 · LAX 11:21 · JFK 14:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.