WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Guru · question 98 of 100

How does the Collections framework handle concurrent modification during iteration, and what are some best practices for avoiding and handling ConcurrentModificationExceptions?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics