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.concurrentpackage, such asConcurrentHashMap,CopyOnWriteArrayList. - Manually synchronize access to the collection using
synchronizedblocks or other synchronization mechanisms. - Use iterators that support safe modification, such as
ListIteratorfor 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
}