标签:
package com.doctor.java8; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This program crashes by throwing java.util.ConcurrentModificationException. Why? Because the * iterators of ArrayList are fail-fast; it fails by throwing ConcurrentModificationException if it detects that * the underlying container has changed when it is iterating over the elements in the container. This behavior * is useful in concurrent contexts when one thread modifies the underlying container when another thread is * iterating over the elements of the container. * * @author sdcuike * * Created on 2016年3月6日 上午10:24:21 */ public class ModifyingList { /** * @param args */ public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("one"); list.add("two"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); list.add("three"); } // one // Exception in thread "main" java.util.ConcurrentModificationException // at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) // at java.util.ArrayList$Itr.next(ArrayList.java:851) // at com.doctor.java8.ModifyingList.main(ModifyingList.java:24) } }
package com.doctor.java8; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Modifying CopyOnWriteArrayList * * Observe that the element “four” added three times is not printed as part of the output. This is because * the iterator still has access to the original (unmodified) container that had three elements. If you create a * new iterator and access the elements, you will find that new elements have been added to aList. * * @author sdcuike * * Created on 2016年3月6日 上午10:32:39 */ public class ModifyingCopyOnWriteArrayList { /** * @param args */ public static void main(String[] args) { List<String> list = new CopyOnWriteArrayList<>(); list.add("one"); list.add("two"); list.add("three"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); list.add("four"); } // one // two // three System.out.println("============"); iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // one // two // three // four // four // four } }
java.util.concurrent.CopyOnWriteArrayList<E>
A thread-safe variant of java.util.ArrayList
in which all mutative operations (add
,set
, and so on) are implemented by making a fresh copy of
the underlying array.
当对CopyOnWriteArrayList调用修改数据操作方法的时候,会copy一份新的内部数组结构,而对原来的内部数组结构没影响。如果要访问新的数据,我们必须重新获取底层新的数组结构的iterator(见上面的程序)。
有关java.util.ConcurrentModificationException
标签:
原文地址:http://blog.csdn.net/doctor_who2004/article/details/50812314