IT追梦者

Programming
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JDK Collection中的fast-fail

Posted on 2012-04-04 19:24  星龙冰  阅读(464)  评论(0编辑  收藏  举报

Java集合框架Iterator具有fast-fail的特性,在创建Iterator以后,如果其他线程对该Collection做了修改或者当前线程调用非Iterator接口对集合做了修改那么就会抛出ConcurrentModificationException 异常,
。以ArrayList为例,其中有一个modCount成员变量来记录对该list修改次数。下面是jdk源码具体描述:

The number of times this list has been structurally modified.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in

     * progress may yield incorrect results. 

jdk5.0中的for each特性实际也是通过迭代器实现(javap看一下字节码就清楚了)。fast-fail的实现也是有些代价的,比如上面的modCount.在使用迭代器遍历或操作Collection时每次都要checkForComodification,因此如果批量对集合进行某些操作,尽量调用批处理操作的接口如:removeAll或者addAll().

 

代码的正确性不要依赖 ConcurrentModificationException这个异常:下面也是jdk doc的描述
Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.