java中的异常“java.util.ConcurrentModificationException”如何解决?

时间:2016-06-18 06:23:11

标签: java exception jena

我有一个遍历某些属性的循环,但在该循环中必须添加一些属性。程序的第一次迭代可以运行,但是从第二次迭代发生以下异常:

Exception in thread "main" java.util.ConcurrentModificationException: Iterator: started at 5, now 113
    at org.apache.jena.tdb.sys.DatasetControlMRSW.policyError(DatasetControlMRSW.java:157)
    at org.apache.jena.tdb.sys.DatasetControlMRSW.access$000(DatasetControlMRSW.java:32)
    at org.apache.jena.tdb.sys.DatasetControlMRSW$IteratorCheckNotConcurrent.checkCourrentModification(DatasetControlMRSW.java:110)
    at org.apache.jena.tdb.sys.DatasetControlMRSW$IteratorCheckNotConcurrent.hasNext(DatasetControlMRSW.java:118)
    at org.apache.jena.atlas.iterator.Iter$4.hasNext(Iter.java:303)
    at org.apache.jena.atlas.iterator.Iter$4.hasNext(Iter.java:303)
    at org.apache.jena.atlas.iterator.Iter$4.hasNext(Iter.java:303)
    at org.apache.jena.atlas.iterator.Iter.hasNext(Iter.java:908)
    at org.apache.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
    at org.apache.jena.util.iterator.Map1Iterator.hasNext(Map1Iterator.java:49)
    at org.apache.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
    at br.com.edu.dataset.ConstrucaoDataSet.main(ConstrucaoDataSet.java:110)
Java Result: 1

方法:

  public ArrayList<Topic> annotate(String originalMarkup) throws Exception {

    PreprocessedDocument doc = _preprocessor.preprocess(originalMarkup);
    Collection<Topic> allTopics = _topicDetector.getTopics(doc, null);

    ArrayList<Topic> bestTopics = _linkDetector.getBestTopics(allTopics, 0.5);

    return bestTopics;
}

....主要......

Property body = model.getProperty("http://data.linkededucation.org/ns/linked-education.rdf#body");
StmtIterator iter = model.listStatements(null, body, (RDFNode) null);

while (iter.hasNext()) {
    Statement stmt = iter.nextStatement();
    String uri = stmt.getSubject().toString();
    String artigo = stmt.getObject().toString();
    ArrayList<Topic> bestTopics = annotator.annotate(artigo);

    Resource lakPaper = model.createResource(uri);
    for (Topic t : bestTopics) {
        lakPaper.addProperty(DC.subject, model.createResource(keyValueProperty)
                .addProperty(key, t.getTitle())
                .addProperty(value, _df.format(t.getWeight())));
        System.out.println(" - " + t.getTitle() + "[" + _df.format(t.getWeight()) + "]");
    }
}

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

如果在迭代时无法避免列表中的并发修改,那么在这种情况下,您可以使用来自CopyOnWriteArrayList包的java.util.concurrent而不是ArrayList。

来自java doc:

  

ArrayList的线程安全变体,其中包含所有可变操作   (添加,设置等)是通过制作新的副本来实现的   底层数组。

因此,您的迭代器永远不会抛出ConcurrentModificationException。 从这里了解更多信息:

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

答案 1 :(得分:1)

当您尝试修改&#34;结构时,会发生并发修改。您正在迭代,即在迭代列表时插入或删除元素。

为避免这种情况,请使用新的集合并相应地执行插入和删除。