java - HashTable有没有采用快速失败机制?
问题描述
1,http://www.yq1012.com/api/jav...由所有类的“collection 视图方法”返回的 collection 的 iterator 方法返回的迭代器都是快速失败 的:在创建 Iterator 之后,如果从结构上对 Hashtable 进行修改,除非通过 Iterator 自身的 remove 方法,否则在任何时间以任何方式对其进行修改,Iterator 都将抛出ConcurrentModificationException。因此,面对并发的修改,Iterator 很快就会完全失败,而不冒在将来某个不确定的时间发生任意不确定行为的风险。由 Hashtable 的键和元素方法返回的 Enumeration 不 是快速失败的。
有地方说因为HashTable做了线程同步,所以没有采用快速失败机制
2,但是源码中hashtable.keySet.iterator 返回的iterator中有 做判断比如说iterator的remove方法 (在类: private class Enumerator<T> implements Enumeration<T>, Iterator<T>中)
public void remove() { if (!iterator)throw new UnsupportedOperationException(); if (lastReturned == null)throw new IllegalStateException('Hashtable Enumerator'); if (modCount != expectedModCount)throw new ConcurrentModificationException(); synchronized(Hashtable.this) {Entry[] tab = Hashtable.this.table;int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e == lastReturned) {modCount++;expectedModCount++;if (prev == null) tab[index] = e.next;else prev.next = e.next;count--;lastReturned = null;return; }}throw new ConcurrentModificationException(); }} public T next() { if (modCount != expectedModCount)throw new ConcurrentModificationException(); return nextElement();}
上面两端代码中都有验证 if (modCount != expectedModCount)
throw new ConcurrentModificationException();所以多线程环境下并发修改hashtable 也是会引起Iterator迭代失败,我代码测试过
这个该怎么理解,请问上面提到的哪种情况是正确的
问题解答
回答1:Hashtable的iterator遍历方式支持fast-fail,用Enumeration不支持fast-fail
相关文章:
1. java基础,求解答。2. python该种情形下应该使用pickle还是csv3. mongodb可以导出数据到excel吗?4. 超链接里的target问题5. python - 怎样在linux下开发flask web应用时查看代码出错(traceback)的地方。6. python3.x - python多进程,不能在同一窗口吗7. javascript - grunt、gulp和webpack有什么区别和各自的优缺点8. clone - git sourceTree克隆仓库时,都不停弹出Password Required弹窗,即时输入正确的git账号密码还是弹出9. python - requests post问题10. mysql控制台没法退出?

网公网安备