前情
这两天一哥们在面试国内大厂问到了,小伙子你知道fail-fast是啥吗??小伙子一脸懵逼,随口来了句中式翻译,“错的快”???,此时此刻的面试官也是一脸懵逼,说道,你觉得怎么走最快就怎么走吧。。。。哈哈,简单的开个玩笑。其实我之前只知道这个玩意的名称,但是不知道底层实现原理是啥,今天我们就来看看到底发生了啥
简述
fail-fast 机制,即快速失败机制,是java集合(Collection)中的一种错误检测机制。当使用迭代器时候,进行一定的改变,就有可能会发生fail-fast,
即抛出ConcurrentModificationException异常。fail-fast机制并不保证在不同步的修改下一定会抛出异常,它只是尽最大努力去抛出,所以这种机制通常用来检测bug。在ArrayList源码中有一定的描述。
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: the fail-fast behavior of iterators
should be used only to detect bugs.
制造异常
public class Main {
public static void main(String[] args) {
testSingleThread();
}
//测试单线程的情况下的异常
public static void testSingleThread() {
System.out.println("testSingleThread()");
List<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(i + "");
}
//创建一个迭代器
Iterator<String> iterator = list.iterator();
int i = 0;
while (iterator.hasNext()) {
if (i == 3) {
list.remove(3); //不安全的做法
// iterator.remove();
}
System.out.print(iterator.next() + " ");
i++;
}
}
//测试多线程的情况下
public static void testConcurrent() {
System.out.println(" testConcurrent()()");
List<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add(i + "");
}
Iterator<String> iterator = list.iterator();
//线程池创建10个线程
ExecutorService executorService = Executors.newFixedThreadPool(10);
//执行线程
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
while(iterator.hasNext())