java.util.concurrent.CopyOnWriteArrayList上的ConcurrentModificationException。<init>(CopyOnWriteArrayList.java:141)

时间:2018-08-09 10:32:29

标签: java

首先:此代码在更多线程下有问题

@Override
public void onLoaded(List<Student> students) {
    if(listener != null){
        listener.onLoaded(students);
    }
}

然后像这样更改

@Override
public void onLoaded(List<Student> students) {
    CopyOnWriteArrayList<Student> copyList = new CopyOnWriteArrayList<Student>(students);
    if(listener != null){
        if(copyList.size() > 0){
            listener.onLoaded(copyList);
        }else{
            listener.onLoaded(students);
        }
    }
}

这也有问题

Fatal Exception: java.util.ConcurrentModificationException
     at java.util.ArrayList$SubList.size(ArrayList.java:1057)
     at java.util.AbstractCollection.toArray(AbstractCollection.java:136)
     at java.util.concurrent.CopyOnWriteArrayList.<init>(CopyOnWriteArrayList.java:141)

在CopyOnWriteArrayList.java

/**
* Creates a new instance containing the elements of {@code collection}.
*/
@SuppressWarnings("unchecked")
public CopyOnWriteArrayList(Collection<? extends E> collection) {
    this((E[]) collection.toArray());
}

AbstractCollection在AbstractCollection中实现Collection

public Object[] toArray() {
    // Estimate size of array; be prepared to see more or fewer elements
    Object[] r = new Object[size()];
    Iterator<E> it = iterator();
    for (int i = 0; i < r.length; i++) {
        if (! it.hasNext()) // fewer elements than expected
            return Arrays.copyOf(r, i);
        r[i] = it.next();
    }
    return it.hasNext() ? finishToArray(r, it) : r;
}

最后是问题。

我只知道我可以使用Lock来修复它,但是我不知道它会导致Android中的ANR,我无法重复该问题,该如何解决?

现在我正在尝试像这样修复它,可以吗?

@Override
public void onLoaded(List<Student> students) {
    final CopyOnWriteArrayList<Student> copyList;
    synchronized (students) {
        copyList = new CopyOnWriteArrayList<Student>(students);
    }
    if(listener != null){
        if(copyList.size() > 0){
            listener.onLoaded(copyList);
        }else{
            listener.onLoaded(students);
        }
    }
}

0 个答案:

没有答案