1. ** 快速报错:**<br /> java容器有一种保护机制,能够防止多个进程同时修改一个容器的内容。对此,java采取快速报错的方式,立刻抛出ConcurrentModficationExcetion异常。<br />
    1. public class FailFast {
    2. public static void main(String[] args) {
    3. Collection<String> c=new ArrayList<>();
    4. c.add("aaa");
    5. c.add("bbbb");
    6. c.add("ccc");
    7. Iterator<String> iterator = c.iterator();
    8. while (iterator.hasNext()) {
    9. System.out.println(iterator.next());//在迭代的时候有进行添加
    10. c.add("fff");
    11. }
    12. }
    13. }
    14. public class FailFast {
    15. public static void main(String[] args) {
    16. Collection<String> c=new ArrayList<>();
    17. Iterator<String> iterator = c.iterator();
    18. c.add("sss");
    19. System.out.println(iterator.next());
    20. }
    21. }
    22. OutPut:抛出异常
    23. Exception in thread "main" java.util.ConcurrentModificationException
    24. at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
    25. at java.util.ArrayList$Itr.next(ArrayList.java:859)
    26. at com.package17.FailFast.main(FailFast.java:12)
    1. 上述的两个程序都会引起快速报错,一个是在迭代的时候添加元素,改变了容器的状态,另一个是在容器获得迭代器之后又有元素加入容器,也导致容器的状态不一致。<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 />
    1. package com.package17;
    2. import java.util.ArrayList;
    3. import java.util.Collection;
    4. import java.util.Iterator;
    5. import java.util.concurrent.ConcurrentHashMap;
    6. import java.util.concurrent.CopyOnWriteArrayList;
    7. import java.util.concurrent.CopyOnWriteArraySet;
    8. public class FailFast {
    9. public static void main(String[] args) {
    10. System.out.println("CopyOnWriteArrayList:");
    11. testList();
    12. System.out.println("CopyOnWriteArraySet:");
    13. testSet();
    14. }
    15. static void testList(){
    16. CopyOnWriteArrayList<String> c=new CopyOnWriteArrayList<>();
    17. c.add("sss");
    18. c.add("aaa");
    19. c.add("sccc");
    20. Iterator<String> iterator = c.iterator();
    21. while (iterator.hasNext()){
    22. c.add("123");
    23. System.out.print(iterator.next()+" ");
    24. }
    25. System.out.println(c);
    26. }
    27. static void testSet(){
    28. CopyOnWriteArraySet <String> c=new CopyOnWriteArraySet<>();
    29. c.add("001");
    30. c.add("002");
    31. Iterator<String> iterator = c.iterator();
    32. while (iterator.hasNext()){
    33. c.add("123");
    34. System.out.print(iterator.next()+" ");
    35. }
    36. System.out.println(c);
    37. }
    38. }
    39. OutPut:
    40. CopyOnWriteArrayList:
    41. sss aaa sccc [sss, aaa, sccc, 123, 123, 123]
    42. CopyOnWriteArraySet:
    43. 001 002 [001, 002, 123]