Note that there are some explanatory texts on larger screens.

plurals
  1. POCopyOnWriteArrayList throwing CurrentModificationException
    text
    copied!<p>I'm occasionally getting a <code>ConcurrentModificationException</code> when I iterate over a list. A Google search informs me that it's probably because I'm altering that list in another thread while iterating over it and that to make this problem go away I should use <code>java.util.concurrent.CopyOnWriteArrayList</code>....</p> <p>... except I already am.</p> <p>Apparently, I'm doing something <i>really</i> stupid somewhere.</p> <p>Does anybody have any insight into how one might induce <code>CopyOnWriteArrayList</code> to toss a <code>ConcurrentModificationException</code>? If it matters, I'm using Java 5.</p> <p><b>Edit:</b> Since the mutators I'm using may matter, I'm modifying this list in two ways:</p> <ul><li>Adding elements to the front. (<code>list.add(0, newElement);</code>)</li> <li>Using subList to let older items fall off the back. (<code>list = list.subList(0, MAX_LIST_SIZE);</code>)</li> </ul> <p>Do those raise red flags? If so, why? My understanding was that because these operations make a copy of the thing first, any existing iterators would be pointing at the unmodified original and would thus not care. Do I have a hole in my knowledge?</p> <p><b>Edit 2:</b> The precise code that's causing the problem is still a bit murky, but I can at least post the exception I'm seeing: <pre><code> java.util.ConcurrentModificationException at java.util.concurrent.CopyOnWriteArrayList$COWSubList.checkForComodification(Unknown Source) at java.util.concurrent.CopyOnWriteArrayList$COWSubList.iterator(Unknown Source) at.... </pre></code></p> <p>... where it points to a for-each loop instantiation in my code.</p> <p>That <code>COWSubList</code> does seem to imply that my call to <code>subList</code> is the root of my problem; I'd still like to understand why.</p> <p><b>Edit 3:</b> <b>*facepalm*</b></p> <p><code>CopyOnWriteArrayList.subList()</code> returns a <code>List</code>, <em>not</em> a <code>CopyOnWriteArrayList</code>. The list it returns is under no implied obligation to provide any of COWAL's protections. Which makes using <code>subList()</code> like this to remove elements a Very Bad Idea.</p> <p>Don't know for certain if this is my culprit, but it's damned suspicious and needs to be corrected regardless.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload