Wednesday, August 22, 2012

Java API for today: ConcurrentModificationException vs CopyOnWriteArrayList

You often iterate over the collection and you rarely add something to it. This sounds like a typical scenario for the Observer design pattern.

List<Listener> listeners = new LinkedList<Listener>();
for(Listener listener : listeners) {
public void addListener(Listener listener){

If you interrupt iterating over the listeners by registering the new one, you will encounter the ConcurrentModificationException thrown by the iterator.

The solution is to use java.util.concurrent.CopyOnWriteArrayList.
List<Listener> listeners = new CopyOnWriteArrayList<Listener>();

In the rare cases when you modify the list of listeners, iterator will work on the snapshot of the original list (created before the modification). Listener's addition will be performed on the copy of the list, that will be eventually merged with the original one.

From now on, stop yelling about the ConcurrentModificationException thrown by your iterators.

No comments:

Post a Comment