I have this little piece of code and it gives me the concurrent modification exception. I cannot understand why I keep getting it, even though I do not see any concurrent modifications being carried out.
import java.util.*;
public class SomeClass {
public static void main(String[] args) {
List<String> s = new ArrayList<>();
ListIterator<String> it = s.listIterator();
for (String a : args)
s.add(a);
if (it.hasNext())
String item = it.next();
System.out.println(s);
}
}
ConcurrentModificationException may arise in both single threaded environment and multi-threaded environment. The main catch is that all the general purpose iterators (like the one used in ArrayList) are all FailFast iterators, which fails when we try to modify one list if one iterator is already iterating over it. Solution - > Use CopyOnWriteArrayList if such scenario is needed by the requirement rather than using ArrayList.
For a complete demo for this, below mentioned code can be used. We just need to change the implementation from CopyOnWriteArrayList to ArrayList.
For more inifo follow this link this may be helpful alot ConcurrentModificationException Java Docs
This didn't work:
This worked:
From the JavaDoc: for ConcurrentModificatoinException: "it is not generally permssible for one thread to modify a Collection while another thread is iterating over it".
It simply means that if you still have an open iterator, you aren't allowed to modify the list because the iterator loop will break. Try moving
ListIterator<String> it = s.listIterator();
till after the for loop.To avoid the
ConcurrentModificationException
, you should write your code like this:A
java.util.ListIterator
allows you to modify a list during iteration, but not between creating it and using it.Between creating the iterator and starting to use the iterator, you added arguments to the list that is to be iterated. This is a concurrent modification.
Create the iterator AFTER you've finished adding elements to the list:
If the above solutions doesn't work properly. You can use old for-loop for iterating a List at the same time adding new items. See the example below: