Java8源码-详解fail-fast

fail-fast 是 Java 容器(如 Vector、ArrayList)中的一种错误机制,当在遍历集合时,如果集合结构被修改,可能会抛出 `ConcurrentModificationException`。在单线程环境下,迭代器自身的 `remove()` 方法修改集合不会抛异常,但集合的 `remove()` 方法会。多线程环境下,两个线程分别进行遍历和修改集合结构也可能触发此异常。实现原理主要通过 `modCount` 记录修改次数,迭代器在遍历时检查此值。避免 fail-fast 的方法是使用 `java.util.concurrent` 包下的线程安全类。
摘要由CSDN通过智能技术生成

细心地朋友看Java容器源码时一定会发现在list()和listIterator()的注释中都有一句话:

The iterators returned by this class’s iterator and listIterator methods are fail-fast.

我看ArrayList源码没认真想fail-fast是什么意思,看Vector源码时又看到了这个词,而且在翻看Set实现类和Map实现类源码时也看到了这个词。fail-fast是什么?本篇文章以Vector为例来详细解说fail-fast。

什么是fail-fast?

下面是Vector中源码的最上部的注释中关于fail-fast的介绍

The iterators returned by this class's {@link #iterator() iterator} and
 * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em></a>:
 * if the vector is structurally modified at any time after the iterator is
 * created, in any way except through the iterator's own
 * {@link ListIterator#remove() remove} or
 * {@link ListIterator#add(Object) add} methods, the iterator will throw a
 * {@link 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.  The {@link Enumeration Enumerations} returned by
 * the {@link #elements() elements} method are <em>not</em> fail-fast.
 *
 * <p>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 {@code ConcurrentModificationException} on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness:  <i>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值