esolve
V2EX  ›  问与答

concurrenthashmap 里 getFirst 函数里的一个问题

  •  
  •   esolve · Mar 27, 2017 · 1340 views
    This topic created in 3361 days ago, the information mentioned may be changed or developed.

    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 replies    2017-03-28 01:29:55 +08:00
    esolve
        1
    esolve  
    OP
       Mar 27, 2017
    HashEntry<K,V> More ...getFirst(int hash) {
    HashEntry<K,V>[] tab = table;
    return tab[hash & (tab.length - 1)];
    }
    SoloCompany
        2
    SoloCompany  
       Mar 28, 2017
    因为这是设计给无锁并发线程安全场景的,如果不先赋值给局部变量,两次对 table 的访问可能返回两个不一样的实例
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   964 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 20:10 · PVG 04:10 · LAX 13:10 · JFK 16:10
    ♥ Do have faith in what you're doing.