0

总而言之,我试图了解 Hashmap resize 函数的多线程竞争条件问题。

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

我已经知道它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值改变?请帮忙确认一下。(原谅我英语不好。)

谢谢。

4

1 回答 1

0

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.

因此

快速失败以立即停止多线程

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

于 2016-03-02T12:27:36.860 回答