Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java how can this throw a ConcurrentModificationException in a single threaded program? [duplicate]

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); }
like image 516
ArturPhilibin Avatar asked Feb 19 '11 16:02

ArturPhilibin


1 Answers

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.

like image 185
aioobe Avatar answered Sep 22 '22 01:09

aioobe