gpt4 book ai didi

java - 为什么我在这个例子中得到了 java.util.ConcurrentModificationException?

转载 作者:行者123 更新时间:2023-11-30 10:25:33 24 4
gpt4 key购买 nike

在下面的代码示例中,我不明白为什么 foo 方法会抛出 ConcurrentModificationException。请帮忙!

private void foo() {
synchronized (map) {
if (map != null && !map.isEmpty()) {
Set<String> it = map.keySet();
ArrayList<String> delArray = new ArrayList<>();
for (String key : it) {
MapItem mapItem = map.get(key);
if (mapItem != null) {
long wakeTime = System.currentTimeMillis() - mapItem.getTimestamp();
if (wakeTime > MY_THRESHOLD) {
if (mapItem.getLock() != null) {
mapItem.getLock().release();
}
delArray.add(key);
}
}
}

if (!delArray.isEmpty()) {
for (String key : delArray) {
map.remove(key);
}
}
}
}
}

我在“for (String key : it) {”行出现异常

private static class MapItem {
private PowerManager.WakeLock lock;
private long timestamp;

public MapItem(PowerManager.WakeLock lock, long timestamp) {
this.lock = lock;
this.timestamp = timestamp;
}

public PowerManager.WakeLock getLock() {
return lock;
}

public long getTimestamp() {
return timestamp;
}
}

最佳答案

您试图在遍历 map 时更改它,这是不允许的。 ConcurrentModificationException :

If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception

关于java - 为什么我在这个例子中得到了 java.util.ConcurrentModificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46138511/

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