Sobes.tech
Middle — Middle+

What methods and approaches are used to prevent the occurrence of ConcurrentModificationException when working with collections in a multithreaded environment?

sobes.tech AI

Answer from AI

The ConcurrentModificationException occurs when a collection is modified during iteration in one thread, while another thread is performing a modification.

To prevent this, the following methods are used:

  • Using thread-safe collections from java.util.concurrent, such as CopyOnWriteArrayList, ConcurrentHashMap. These collections allow safe modification and reading from different threads.

  • Synchronizing access to the collection. You can use synchronized blocks or methods to ensure that modification and iteration do not overlap.

  • Cloning the collection before iteration. Iteration occurs over a copy, which excludes ConcurrentModificationException.

  • Using iterators that support modifications (e.g., ListIterator), but avoiding structural modifications of the collection outside the iterator.

Example with CopyOnWriteArrayList:

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("one");
list.add("two");

for (String item : list) {
    // It is safe to modify list inside the loop
    list.add("three");
}

Thus, the choice of approach depends on performance requirements and the nature of operations with the collection.