java – CopyOnWriteArrayList throwing CurrentModificationException
When I traverse a list, I occasionally get a concurrentmodificationexception Google search informed me that this may be because I changed the list in another thread, iterated it at the same time, and made the problem disappear. I should use Java util. concurrent. CopyOnWriteArrayList ….
Except that I have
Obviously, I'm doing something really stupid
Does anyone have any insight into how to trigger copyonwritearraylist to throw concurrentmodificationexception? If important, I use Java 5
Edit: since the mutator I use may be important, I modify this list in two ways:
>Add an element to the front (list. Add (0, newelement);) > Use the sublist to drop older items from the back (list = list.subList(0,MAX_LIST_SIZE);)
Do those raise red flags? If so, why? My understanding is that since these operations copy these things first, any existing iterator will point to the unmodified original, so I won't care Do I know there's a hole?
Edit 2: the exact code that caused the problem is still a little dim, but I can at least publish the exceptions I saw:
java.util.ConcurrentModificationException at java.util.concurrent.CopyOnWriteArrayList$COWSubList.checkForComodification(UnkNown Source) at java.util.concurrent.CopyOnWriteArrayList$COWSubList.iterator(UnkNown Source) at....
... it points to the for - each loop instantiation in my code
Cowsublist seems to imply that my call to the sublist is the root of my problem; I still wonder why
Edit 3: * faceperm*
CopyOnWriteArrayList. Sublist() returns a list instead of a copyonwritearraylist The returned list has no implicit obligation to provide any protection for cowal This makes it a bad idea to use such a sublist () to delete elements
I don't know if this is my culprit, but it is suspicious and needs to be corrected
Solution
CopyOnWriteArrayList. Sublists throw concurrentmodificationexceptions. If the list is included, change it from the following:
public class ListTest { private static List<int[]> intList; public static void main (String[] args) { CopyOnWriteArrayList<Integer> cowal = new CopyOnWriteArrayList<Integer>(); cowal.add(1); cowal.add(2); cowal.add(3); List<Integer> sub = cowal.subList(1,2); cowal.add(4); sub.get(0); //throws ConcurrentModificationException } }