gpt4 book ai didi

java - 单独列表上的 ConcurrentModificationException 不清楚

转载 作者:行者123 更新时间:2023-11-30 03:04:31 25 4
gpt4 key购买 nike

在类里面我有这两种方法:

public void notifyResult(List<Road> result) {
ArrayList<RoadOverlay> tempRoads = new ArrayList<>();

for(Road road:result){
// Computes and stores the overlays
// ...
tempRoads.add(new RoadOverlay());
}
//switch field when update is done
this.positions = tempRoads;
}
}

private void drawRoadsVO(GL gl) {
// keep a reference on the current instance of the field
// to avoid concurrent modification in notifyResult
ArrayList<RoadOverlay> positionsCopy = this.positions;
int vertexCount = 0;
for (RoadOverlay road : positionsCopy) { //ConcurrentModificationException here
// ...
}
}

两种方法都在单独的线程中运行。在渲染内部,我没有对列表进行任何更改,据我了解,我在单独的列表上工作,那么这如何产生 CME?我正在努力解决这个问题,任何线索都会受到欢迎。我尽可能避免使用同步带来的损失。

问候

编辑了代码中的注释

最佳答案

通常最好制作列表的完整副本

ArrayList<RoadOverlay> positionsCopy = new ArrayList<Integer>(this.positions);

至于ConcurrentModificationException,您的代码看起来不错,可能是您正在其他一些类方法中修改当前的this.positions?请注意,您的 this.positions 变量应声明为 volatile

这是ArrayList迭代器的next()方法

public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}

ConcurrentModificationException 仅在列表的 elementData 结构被修改的情况下才会抛出

Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.

关于java - 单独列表上的 ConcurrentModificationException 不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35151676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com