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. docker镜像push报错2. Javascript-JSON.parse:数据意外结束-使用有效JSON时出错。我究竟做错了什么?3. 收缩页面显示的图片怎么写4. javascript - 如何使用nodejs 将.html 文件转化成canvas5. python - django 项目的 migrations 目录是否应该提交到 git6. mysql - SELECT 多個資料表及多個欄位7. css - 盒模型布局,隐藏内部元素,外围高度居然没有改变?求解决办法8. javascript - svg小白,想要在svg里面插入图片9. java - 使用 RedisTemplate 操作数据10. PHP5.5.38.0 Apache2.4.23.0服务崩溃 系统日志php_curl.dll模块报

网公网安备