Sobes.tech
Junior — Middle

What methods can be used to avoid ConcurrentModificationException when working with collections in a multithreaded environment?

sobes.tech AI

Answer from AI

To avoid the ConcurrentModificationException when working with collections in a multithreaded environment, you can use the following methods:

  • Use thread-safe collections from the java.util.concurrent package, such as ConcurrentHashMap, CopyOnWriteArrayList.
  • Manually synchronize access to the collection using synchronized blocks or other synchronization mechanisms.
  • Use iterators that support safe modification, such as ListIterator for lists.
  • Create copies of collections for iteration (e.g., via new ArrayList<>(originalList)) to avoid modifying the original collection during traversal.

Example of using CopyOnWriteArrayList:

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("item1");
for (String item : list) {
    list.add("item2"); // will not cause ConcurrentModificationException
}
What methods can be used to avoid… - sobes.tech