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

标签 java concurrentmodification

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

相关文章:

java - JPA 获取连接实体返回递归获取循环

java - ConcurrentModificationException,需要澄清

java - 我该如何修复此错误 java.util.ConcurrentModificationException

java - 为什么列表的反向子列表的List.addAll导致ConcurrentModificationException

java.util.ConcurrentModificationException 但我没有删除

java - 我到底需要同步什么,对象或对象内的数据

java - 如何在 String.xml 中使用两个具有相同名称的不同字符串值?

java - JDBC : accessing remote Mysql database securely?

java - 访问 Executor Service Future 列表时出现 ConcurrentModificationException

java - 多列上的 DISTINCT 查询不起作用 - Google App Engine 数据存储区