In Java Collections, concurrent modification occurs when a collection is modified while it is being iterated. This can result in a ConcurrentModificationException being thrown at runtime. To avoid this exception, there are several approaches you can take:
Use a concurrent collection: Collections such as ConcurrentHashMap, ConcurrentSkipListMap, and CopyOnWriteArrayList are designed to be modified concurrently and can be iterated over without throwing ConcurrentModificationExceptions.
Use an iterator: Instead of using a for-each loop, use an iterator to iterate over the collection. The iterator’s remove() method can be used to remove elements safely from the collection during iteration.
Use a copy of the collection: Make a copy of the collection before iterating over it. This avoids concurrent modification because the iteration is performed on a copy of the collection, not the original.
Synchronize the iteration: Synchronize the iteration using the same lock that is used to modify the collection. This ensures that the iteration and modification are mutually exclusive.
Here is an example of how to use an iterator to safely remove elements from a collection during iteration:
List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three", "four"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("two")) {
iterator.remove();
}
}
In this example, the iterator’s remove() method is used to safely remove the element "two" from the list during iteration.
It is important to note that while these approaches can help avoid ConcurrentModificationExceptions, they do not guarantee thread-safety. If multiple threads are modifying the same collection concurrently, you will need to use additional synchronization mechanisms to ensure thread-safety.