DataSetObservable中关于ConcurrentModificationException异常的避免

2017/3/9 22:58 下午 posted in  Android  
public class DataSetObservable extends Observable<DataSetObserver> {
    public void notifyChanged() {
        synchronized(mObservers) {
            // since onChanged() is implemented by the app, it could do anything, including
            // removing itself from {@link mObservers} - and that could cause problems if
            // an iterator is used on the ArrayList {@link mObservers}.
            // to avoid such problems, just march thru the list in the reverse order.
            for (int i = mObservers.size() - 1; i >= 0; i--) {
                mObservers.get(i).onChanged();
            }
        }
    }
    ...
}    

之前版本的代码

synchronized (mObservers) {
        for (DataSetObserver observer : mObservers) {
            observer.onInvalidated();
        }
}

java中foreach方式遍历使用了Iterator迭代器,出现ConcurrentModificationException的原因是因为在通过Iterator遍历时直接调用了集合类的remove方法等,导致modCount不一致。如果遍历、remove都使用Iterator或者都使用for,就不会有这个问题。

参考

How to deal with ConcurrentModificationException while doing swapCursor()?
How does the Java for each loop work?