esolve
V2EX  ›  问与答

concurrenthashmap 里 getFirst 函数里的一个问题

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