在下面的代码示例中,我不明白为什么 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/