missedMSRB是一个列表,其中包含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;

    }

最佳答案

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)));

关于java - 此代码块的并发修改异常,请帮助?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27925960/

10-09 13:48