疾速失败 也就是fail-fast ,它是java 汇合的一种谬误检测检测机制。当多个线程对汇合进行构造上的扭转操作时,就有可能产生fail-fast 工夫。例如,假如两个线程A,B。线程A 通过迭代器(Iterator)在遍历汇合X 中的元素时,线程B批改了汇合X 的构造,删除或新增元素,那么这个时候程序就会抛出java.util.ConcurrentModificationException
异样,从而产生fail-fast事件。
例如:
public static void main(String[] args) { HashMap<String ,Integer> hashMap = new HashMap<>(); hashMap.put("a", 1); hashMap.put("b", 2); hashMap.put("c", 3); Set set = hashMap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); hashMap.put("进行增加操作", 4); System.out.println("此时 hashMap 长度为" + hashMap.size()); } }
output:
a=1此时 hashMap 长度为4Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1493) at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1526) at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1524) at FastFail.main(FastFail.java:16)
Iterator 反对从源汇合中平安地删除对象,删除的办法在Iterator上调用remove()办法。这样做的益处是能够防止ConcurrentModificationException异样产生。
public static void main(String[] args) { HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("a", 1); hashMap.put("b", 2); hashMap.put("c", 3); Iterator iterator = hashMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = (Entry<String, Integer>) iterator.next(); System.out.println(entry); if("b".equals(entry.getKey())){ iterator.remove(); System.out.println("删除胜利"); } } }
output:
a=1b=2删除胜利c=3