I was reading this "Freuqent Java concurrency problems" question and got confused by an answer talking about java.util.ConcurrentModificationException.
My understanding of the answer is that this can occur in a single-threaded program. How or what conditions cause the following code to throw the exception?
List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c"));
for (String string : list) { list.remove(string); }
This snippet will always throw a ConcurrentModificationException
.
The rule is the following: You may not modify (add or remove elements from the list) while iterating over it using an Iterator (which happens when you use a for-each loop).
Note however that you are allowed to modify the list through the iterator (because then it is aware of the modification, and can take it into account) using the Iterator.remove
or ListIterator.add
.
From the docs:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
The word concurrent here refers to that you're modifying the list during traversal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With