** 快速报错:**<br /> java容器有一种保护机制,能够防止多个进程同时修改一个容器的内容。对此,java采取快速报错的方式,立刻抛出ConcurrentModficationExcetion异常。<br />
public class FailFast {
public static void main(String[] args) {
Collection<String> c=new ArrayList<>();
c.add("aaa");
c.add("bbbb");
c.add("ccc");
Iterator<String> iterator = c.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());//在迭代的时候有进行添加
c.add("fff");
}
}
}
public class FailFast {
public static void main(String[] args) {
Collection<String> c=new ArrayList<>();
Iterator<String> iterator = c.iterator();
c.add("sss");
System.out.println(iterator.next());
}
}
OutPut:抛出异常
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.package17.FailFast.main(FailFast.java:12)
上述的两个程序都会引起快速报错,一个是在迭代的时候添加元素,改变了容器的状态,另一个是在容器获得迭代器之后又有元素加入容器,也导致容器的状态不一致。<br /> <br />二、![image.png](https://cdn.nlark.com/yuque/0/2021/png/12862216/1619097716244-9c5feb9f-87ec-41a5-83ff-c0711c9f9d18.png#clientId=ua4b14b63-f65e-4&from=paste&height=18&id=ue1a692e2&name=image.png&originHeight=35&originWidth=857&originalType=binary&size=18798&status=done&style=none&taskId=uea18aa96-a5a2-4e49-879f-94262fb4bcc&width=429)都使用了可以避免快速快速报错的技术<br />
package com.package17;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
public class FailFast {
public static void main(String[] args) {
System.out.println("CopyOnWriteArrayList:");
testList();
System.out.println("CopyOnWriteArraySet:");
testSet();
}
static void testList(){
CopyOnWriteArrayList<String> c=new CopyOnWriteArrayList<>();
c.add("sss");
c.add("aaa");
c.add("sccc");
Iterator<String> iterator = c.iterator();
while (iterator.hasNext()){
c.add("123");
System.out.print(iterator.next()+" ");
}
System.out.println(c);
}
static void testSet(){
CopyOnWriteArraySet <String> c=new CopyOnWriteArraySet<>();
c.add("001");
c.add("002");
Iterator<String> iterator = c.iterator();
while (iterator.hasNext()){
c.add("123");
System.out.print(iterator.next()+" ");
}
System.out.println(c);
}
}
OutPut:
CopyOnWriteArrayList:
sss aaa sccc [sss, aaa, sccc, 123, 123, 123]
CopyOnWriteArraySet:
001 002 [001, 002, 123]