1、会报java.util.ConcurrentModificationException的代码private static void fastFailSceneWhenRemove(Map<String, String> source) { for (Map.Entry<String, String> entry : source.entrySet()) { if (entry.getKey().contains("1")) { source.remove(entry.getKey()); } } System.out.println(source);}
2、使用Iterator的Remove方法,可以解决此问题。可以正常运行的代码:private stat足毂忍珩ic void commonSceneWhenRemove(Map<String, String> source) { Iterator<Map.Entry<String, String>> iterator = source.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); if (entry.getKey().contains("1")) { iterator.remove(); } } System.out.println(source); }
3、java.util.HashMap中抛java.util.ConcurrentModificationException的两个场景可以看到,是否抛异常是由modCount != expectedModCount来决定的
4、java.util.HashMap的remove方法的源代码可以看到:remove方法执行之后,java.util.HashMap.modCount++,但java.util.HashMap.HashIterator.expectedModCount的值没有发生变化
5、java.util.HashMap.HashIterator的remove方法的源代码可以看出:remove方法执行之后,modCount和expectedModCount的值是相等的。因此不会抛java.util.ConcurrentModificationException
6、完整的代码:package chapter1;import java.util.HashMap;import java.util.Iterator;import 枣娣空郅java.util.Map;/** * Created by MyWorld on 2016/3/3. */public class FastFailResolver { public static void main(String[] args) { Map<String, String> source = new HashMap<String, String>(); for (int i = 0; i < 10; i++) { source.put("key" + i, "value" + i); } System.out.println("Source:" + source); // fastFailSceneWhenRemove(source); commonSceneWhenRemove(source); } private static void commonSceneWhenRemove(Map<String, String> source) { Iterator<Map.Entry<String, String>> iterator = source.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); if (entry.getKey().contains("1")) { iterator.remove(); } } System.out.println(source); } private static void fastFailSceneWhenRemove(Map<String, String> source) { for (Map.Entry<String, String> entry : source.entrySet()) { if (entry.getKey().contains("1")) { source.remove(entry.getKey()); } } System.out.println(source); } }