集合初探--Fail-Fast机制
Fail-Fast机制
·在系统发生错误后,立即作出响应,阻止错误继续发生。
集合中的“Fail-Fast”机制
·集合在其返回遍历器(Iterator)后任何时候发生变化,将会导致遍历器抛出ConcurrentModificationException异常的机制。
·这种变化不包括遍历器本身调用remove方法移除元素。
·ConcurrentModificationException异常不一定要并发下才会产生。比如:
Map map = new HashMap(); for (int i = 1; i < 10; i++) { map.put(i, i); } for (Iterator ite = map.entrySet().iterator(); ite.hasNext();) { Map.Entry entry = (Map.Entry) ite.next();// 抛出异常位置 // // 调用Iterator.remove()不会抛出异常 // ite.remove(); // 调用map.remove()会抛出异常 map.remove(entry.getKey()); }
HashIterator() { expectedModCount = modCount; if (size > 0) { // advance to first entry Entry[] t = table; while (index < t.length && (next = t[index++]) == null) ; } }
final Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }