并发修改异常

时间:2014-08-13 06:53:22

标签: java android

我的以下代码抛出并发修改异常,我无法解决它。救命啊!

  {
    long now = new Date().getTime();
    Set<String> keyset = requests.keySet();
    Iterator<String> iterator = keyset.iterator();

    while (iterator.hasNext()) {
        String packetId = iterator.next();
        RequestHolder entry = requests.get(packetId);
        if (entry.isExpired(now)) {
            entry.getListener().onTimeout(packetId);
            iterator.remove();
        }
    }
  }

2 个答案:

答案 0 :(得分:1)

替换你的代码
long now = new Date().getTime();
Iterator<Map.Entry<String, RequestHolder>> iterator = requests.entrySet().iterator();

while (iterator.hasNext()) {
    Map.Entry<String, RequestHolder> entry = iterator.next();
    String packetId = entry.getKey();
    RequestHolder requestHolder = entry.getValue();
    if (requestHolder.isExpired(now)) {
        requestHolder.getListener().onTimeout(packetId);
        iterator.remove();
    }
}

解决方案是迭代整个集合而不是遍历密钥集,使用密钥集迭代器再次访问集合中的条目并从密钥集中删除条目

答案 1 :(得分:0)

用这个替换你的while循环...

for (Entry<String, RequestHolder> entryElem : requests.keySet()) {
            String packetId = entryElem.getValue();
        RequestHolder entry = requests.getValue.get(packetId);
        if (entry.isExpired(now)) {
            entry.getListener().onTimeout(packetId);
            iterator.remove();
        }
    }