【问题标题】:Why Hashmap fail-fast not happen in the resize function? (for multiple thread race condition issue)为什么 Hashmap fail-fast 不会在 resize 函数中发生? (对于多线程竞争条件问题)
【发布时间】:2016-06-15 06:41:44
【问题描述】:

所有,我试图了解 Hashmap resize 函数的多线程竞争条件问题。

正如我从here 那里读到的。竞争条件问题会导致条目列表的无限循环链接。

我已经知道Hashmap 具有快速故障机制来立即停止多个线程访问它。下面的代码说明了这一点。

if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

我的问题是为什么快速失败不适用于调整大小功能? 我调试的代码如下。(jdk1.7)

void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

因为for 不使用Iterator

更新

或者因为resize函数没有使用Put*Remove*Clear*方法会导致modCount值改变?请帮忙确认一下。(原谅我英语不好。)

谢谢。

【问题讨论】:

    标签: java multithreading fail-fast


    【解决方案1】:

    HashMap 的 Javadoc 对此进行了解释:ConcurrentModificationException 是检测常见编程错误(在迭代时修改)的最佳努力。

    
     * Note that the fail-fast behavior of an iterator cannot be guaranteed
     * as it is, generally speaking, impossible to make any hard guarantees in the
     * presence of unsynchronized concurrent modification.  Fail-fast iterators
     * throw ConcurrentModificationException on a best-effort basis.
     * Therefore, it would be wrong to write a program that depended on this
     * exception for its correctness: the fail-fast behavior of iterators
     * should be used only to detect bugs.
    

    这样

    fail-fast 立即停止多线程

    不保证。并且任何不同步的并发修改都可能导致未定义的状态。

    【讨论】:

    • 这是来自 OP 发布的链接“当两个或更多线程看到需要调整相同哈希图的大小时,他们可能最终将旧存储桶的元素添加到"所以本质上,这个陈述可以从你的答案中延伸出来。我说的对吗?
    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2016-10-12
    • 2013-12-31
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多