ConcurrentModificationException error android

问题描述 投票:0回答:1

我在这里努力了解为什么我在这里得到ConcurrentModificationException ...

这是我的代码:

var adapterCurrentList : PagedList<WorkPackagesQuery.WorkPackage>? = null
val workPackagesArrayList = arrayListOf<WorkPackagesQuery.WorkPackage>()

fun turnPagedListIntoArrayList(searchString: String) {
    workPackagesArrayList.clear()
    val tempCurrentArray = Collections.synchronizedList(adapterCurrentList)
    synchronized(tempCurrentArray) {

        for ((index, workPackage) in tempCurrentArray.withIndex()) { //exception is thrown here. 
            if (workPackage.id().contains(searchString)) {
                workPackagesArrayList.add(workPackage)
            }
        }
    }

}

我想念的是什么?我没有在迭代时修改tempCurrentArray ...第一次使用搜索字符串运行正常,第二次使用不同的搜索字符串,则抛出异常。

这里是堆栈跟踪:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bechtel.pf.mock, PID: 18686
java.util.ConcurrentModificationException
    at java.util.ArrayList$SubList.size(ArrayList.java:1057)
    at androidx.paging.PagedStorage.get(PagedStorage.java:170)
    at androidx.paging.PagedList.get(PagedList.java:410)
    at java.util.AbstractList$Itr.next(AbstractList.java:358)
    at com.bechtel.pf.ui.workpackages.WorkPackagesViewModel.turnPagedListIntoArrayList(WorkPackagesViewModel.kt:48)
    at com.bechtel.pf.ui.workpackages.WorkPackagesViewModel.pareDownArrayForSearch(WorkPackagesViewModel.kt:59)
    at com.bechtel.pf.ui.workpackages.WorkPackagesFragment$onCreateView$$inlined$addTextChangedListener$1.afterTextChanged(TextView.kt:101)
android kotlin concurrentmodification
1个回答
0
投票

您的问题是workPackagesArrayList.clear(),其实现(ArrayList.java)如下:

public void clear() {
    modCount++;

    // clear to let GC do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

如您所见,它不是线程安全的。

您应该在workPackagesArrayList.clear()上同步呼叫。

© www.soinside.com 2019 - 2024. All rights reserved.