A ConcurrentModificationException is a runtime exception that occurs when an application concurrently modifies an object in a way that violates the object’s concurrent modification rules.
This exception can occur when multiple threads are attempting to modify an object concurrently, and the object is not designed to be modified concurrently. It can also occur when a single thread is iterating over a collection and modifies the collection in some way, such as by adding or removing an element, while the iteration is in progress.
Here is an example of how a ConcurrentModificationException might be thrown:
To avoid ConcurrentModificationExceptions, you can:
Use thread-safe collections such as Vector or CopyOnWriteArrayList instead of non-thread-safe collections like ArrayList.
Use synchronization to ensure that only one thread can modify the collection at a time.
Use an iterator that supports the remove() method and call that method instead of modifying the collection directly.
xxxxxxxxxx
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("a")) {
list.remove(s); // This will throw a ConcurrentModificationException
}
}
https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html