Video in progress
Does ConcurrentModificationException only appear with multiple threads?
List<String> names = new ArrayList<>(List.of("Ali", "Vali", "Gani"));
for (String n : names) {
if (n.startsWith("V")) {
names.remove(n);
}
}
No, it often appears on a single thread: when you iterate a collection with for-each and modify it directly. This is the "fail-fast" iterator's check and has nothing to do with thread safety.
📖 Answer
This code throws a ConcurrentModificationException even with a single thread. ArrayList has a modCount counter inside; on every next() the iterator compares it with the initial value. names.remove(n) incremented the counter, so the iterator fails with "someone modified the list".
(An interesting case: if the removed element is the second to last one, the loop can end without an exception, because hasNext() returns false. That is an accident, so don't count on it.)
The right ways:
names.removeIf(n -> n.startsWith("V"));
// or through the iterator
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().startsWith("V")) it.remove();
}
With multiple threads, the fail-fast check is not a guarantee; it works "on a best-effort basis". Even if no exception is thrown, the data may be corrupted. That is why in a parallel setting you need concurrent collections, whose iterators are "weakly consistent" and don't throw this exception.
Sign up to mark studied questions and save your progress.