异常java.util.ConcurrentModificationException
程序员文章站
2022-05-31 14:09:50
...
异常java.util.ConcurrentModificationException
控制台出现提示如下:
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at cn.whu.sendimage.pm.Crawler.reGet(Crawler.java:64)
at cn.whu.sendimage.pm.timer.ReGetTasker.run(ReGetTasker.java:18)
at cn.whu.sendimage.pm.timer.Tasker.run(Tasker.java:22)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
源代码:
//这个是一个map:键是时间(一个小时),如20180624020000;值是此时间段(一个小时)需要重新请求的url.
private static final Map<String, Set<String>> errorAndRequestAgain = new HashMap<String, Set<String>>();
//重新请求所有map中的url.如果key中没有值,那么就删除此键值对。
for (String key : errorAndRequestAgain.keySet()) {
System.out.println(key);
System.out.println(errorAndRequestAgain.get(key).size());
System.out.println(errorAndRequestAgain.get(key));
if (errorAndRequestAgain.get(key).size() == 0) {
errorAndRequestAgain.remove(key);
} else {
logger.info("还有"+key+"时刻未处理,共"+errorAndRequestAgain.get(key).size()+"站点,准备重新下载");
JSONArray httpJson = getHttpJson(new ArrayList<String>(errorAndRequestAgain.get(key)), key);
List<String[]> list = jsonArrayTOList(httpJson);
String fileName = key + ".txt";
ToFileUtil.WriteStringToTxtFile(list, downfilePath + fileName);
}
}
更改为:
Iterator<Entry<String, Set<String>>> it = errorAndRequestAgain.entrySet().iterator();
while(it.hasNext()){
Entry<String, Set<String>> entry=it.next();
String key=entry.getKey();
if (errorAndRequestAgain.get(key).size() == 0) {
it.remove();
}else {
logger.info("还有"+key+"时刻未处理,共"+errorAndRequestAgain.get(key).size()+"站点,准备重新下载");
JSONArray httpJson = getHttpJson(new ArrayList<String>(errorAndRequestAgain.get(key)), key);
List<String[]> list = jsonArrayTOList(httpJson);
String fileName = key + ".txt";
ToFileUtil.WriteStringToTxtFile(list, downfilePath + fileName);
}
}