How Can I Get ConcurrentModificationException Despite Using Synchronized?
It's common to assume that using the synchronized keyword prevents all concurrency issues. However, it only ensures that one thread at a time can access a synchronized block of code. It doesn't prevent modifications to the collection being iterated upon.
Consider the following code:
public synchronized X getAnotherX() { if (iterator.hasNext()) { X b = iterator.next(); String name = b.getInputFileName(); ... return b; } else { return null; } }
The synchronized declaration header only ensures that the entire method is executed by one thread at a time. However, it doesn't prevent the collection that the iterator is accessing from being modified by other threads.
Why Does ConcurrentModificationException Occur?
ConcurrentModificationException typically occurs when you modify the collection being iterated upon within the iteration loop. For instance, the following code will cause this exception:
Iterator iterator = collection.iterator(); while (iterator.hasNext()) { Item item = (Item) iterator.next(); if (item.satisfiesCondition()) { collection.remove(item); } }
In this case, you should use the iterator.remove() method to remove elements instead. If you need to add to the collection, you can't rely on synchronized methods. However, if you're dealing with a list, you can use the ListIterator subtype, which provides an add() method.
The above is the detailed content of Why Do I Get ConcurrentModificationException Even When Using `synchronized`?. For more information, please follow other related articles on the PHP Chinese website!