In the following code sample, I don't understand why foo method throws ConcurrentModificationException. Please help!
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);
}
}
}
}
}
I am getting exception on "for (String key : it) {" line
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;
}
}