0

I am confused by one specific point regarding synchronization feature of LinkedHashMap. Here are the related Javadoc where I am confused. My confusion point is, why remove method is special here, which is mentioned by -- "except through the iterator's own remove method"?

http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

The iterators returned by the iterator method of the collections returned by all of this class's collection view methods are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

thanks in advance, Lin

4

3 回答 3

4

Basically, you're not allowed to structurally modify a map while iterating over it, since doing so would invalidate the iterator.

Iterator.remove() is specifically exempt from this, to enable you to easily write code like this:

Iterator<E> it = coll.iterator();
while (it.hasNext()) {
  E val = it.next();
  if (some_condition) {
    it.remove();
  }
}
于 2013-02-03T13:57:17.940 回答
2

这并不特别,它是使用迭代器时从集合中删除某些项目的正常方式。如果一个元素在迭代器“外部”被移除,则给定集合的迭代器视图与实际集合相比变得不一致,因为迭代器无法知道元素被移除的原因或方式。

迭代器可以是不同的类型。有些迭代器在集合的给定状态上“操作”,在这种情况下,在迭代器之外修改集合没有任何区别。这对于不可变集合很常见。另一种类型的迭代器是“快速失败”的迭代器,一旦它发现迭代器现在正在查看集合的旧状态(即集合是从外部修改的),就会抛出异常。如文档中所述,LinkedHashMap使用快速失败的迭代器。

于 2013-02-03T13:57:57.137 回答
1

它并不特别,它在 上获得了一种锁,LinkedHashMap这样你就可以通过它的remove方法来删除元素。

这是因为,如前所述:

结构修改是添加或删除一个或多个映射的任何操作,或者在访问排序的链接哈希映射的情况下,影响迭代顺序。

这意味着您在数据结构上有一个待处理的迭代器,允许任何修改都会在确定性行为方面产生问题(因为随着底层结构的变化,迭代器会变得不一致)。因此,如果您有一个开放的迭代器,只要您调用任何方法,实现就会使任何结构修改失败并出现异常。

于 2013-02-03T13:58:18.833 回答