---
title: "容器Iterator的fail-fast"
author: "zzy1943"
date: "2010-05-05T22:33:40Z"
tags: []
categories: ["编程语言"]
slug: "iterator-fail-fast"
draft: false
lastmod: "2010-05-05T22:34:57Z"
id: 659941
url: "https://zzy1943.iteye.com/blog/659941"
---

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.
  fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, 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.

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.

    继承自AbstractList的List：LinkedList,ArrayList,Vector,Stack的Iterator都有这种属性
     PriorityQueue的Iterator也有这种属性.

    中种特性的实现方法是借助于一个modCount成员变量，记录structual modification的次数，在Iterator初始化时，让它的成员变量expectedModCount等于modCount，这样在Iterator做遍历时，如果发现 expectedModCount!= modCount就说明容器的内容发生了改变，抛出ConcurrentModificationException异常