missMSRB是一个包含2187个元素的列表,当我尝试运行以下代码段时
List<List<String>> subList = getSubList(missedMSRB, 1000);
for (List<String> subMSRB : subList) {
StringBuffer sql = new StringBuffer(NamedQueries.msSQL);
sql.append("(");
for (int i1 = 0; i1 < subMSRB.size(); i1++) { //Line 463 Throws Exception
if (i1 < subMSRB.size() - 1) {
sql.append("?,");
} else {
sql.append("? )");
}
} ....
代码失败,随后出现异常的任何建议,为什么我要进行并发修改以及如何摆脱相同的
13 Jan 2015 10:42:58,974 [main] ERROR RunAnalytics: General Error: null
java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1169)
at java.util.ArrayList$SubList.size(ArrayList.java:998)
at com.abc.Analytics.RunAnalytics.getCountCheck(RunAnalytics.java:463)
at com.abc.Analytics.RunAnalytics.analyticsExecute(RunAnalytics.java:342)
at com.abc.Analytics.RunAnalytics.main(RunAnalytics.java:84)
下面的剩余代码
PreparedStatement psMSQL2 = msSQL.prepareStatement(sql.toString());
psMSQL2.setString(1, runDate);
psMSQL2.setString(2, runDate2);
int i = 3;
for (String s : subMSRB) {
psMSQL2.setString(i, s.trim());
i++;
}
ResultSet msSQL = psMSQL2.executeQuery();
logger.debug("SQL executed");
while (msSQL.next()) {
missedMSRB.remove(msSQL.getString(1));
}
getSubList impl // 已更正
public static List<List<String>> getSubList(List<String> inputList, int subListSize) {
int listSize = inputList.size();
int noOfLoops = listSize / subListSize;
int remainingListSize = listSize % subListSize;
List<List<String>> subList = new ArrayList<List<String>>();
for (int i = 0; i < noOfLoops; i++) {
int fromIndex = i * subListSize;
int toIndex = (fromIndex) + subListSize;
subList.add(new ArrayList<String>(inputList.subList(fromIndex, toIndex)));
if ((remainingListSize != 0)
&& (toIndex == (listSize - remainingListSize))) {
subList.add(new ArrayList<String>(inputList.subList(toIndex, listSize)));
}
}
return subList;
}
答案 0 :(得分:2)
在getSubList
中,您可以使用inputList.subList
创建多个列表。 List
中实现的ArrayList
中的此方法不会创建新的列表。相反,它会返回inputList
的视图,因此由inputList
支持。
对inputList
的任何修改都会对子列表产生影响。您已将missedMSRB
作为inputList
传递,因此对missedMSRB
的任何修改都会影响subList
因此,当您在外部missedMSRB.remove
圈内致电for
时,您会为ConcurrentModification
中的所有列表创建subList
。然后,当您在subList
中检查其中一个列表的大小时,会抛出ConcurrentModificationException
要解决此问题,您可以创建新列表,而不是直接使用subList
的结果:
subList.add(new ArrayList<String>(inputList.subList(fromIndex, toIndex)));