简体   繁体   English

同步后的Java并发修改异常

[英]Java Concurrent Modification Exception after synchronizing

I have a LinkedList of objects im trying to iterate over(using an iterator), see if they have any collision, if so, remove it from the list. 我有一个对象的LinkedList我正在尝试迭代(使用迭代器),看它们是否有冲突,如果有,请将其从列表中删除。 However, I am getting a concurrent modification exception. 但是,我遇到了并发修改异常。 I put it in a synchronized block, and I also tried catching the error in a try catch block, neither seem to help at all, the code is here: 我将其放在同步块中,并且我还尝试在try catch块中捕获错误,但似乎都没有帮助,代码在这里:

private void updateTP() {
    synchronized (toiletpaper) {
        Iterator<ToiletPaper> iter = toiletpaper.iterator();
        while (iter.hasNext()) {
            ToiletPaper tp = iter.next();
            tp.update(1000, 700);
            if (toilet.overlaps(tp)) {
                System.out.println("tp splash!");
                toiletpaper.remove(tp);
                menu.removeLife();
            }
        }
    }
}

Any thoughts on the problem would be appreciated, I looked through here and google, and all of them said either catch the exception or synchronize it, which neither seem to work so... please help. 关于这个问题的任何想法都将不胜感激,我在这里和google中浏览了一下,他们所有人都说捕获异常或同步异常,这似乎都不起作用,请帮助。

To avoid the exception, use iter.remove() instead. 为避免异常,请改用iter.remove() This will remove the element via the iterator instance, rather than the current call, which searches and removes from the list separately - that is, a concurrent modification. 这将通过迭代器实例而不是当前调用删除迭代器实例,该实例分别搜索并从列表中删除-即并发修改。

It is throwing an exception because you're modifying the collection directly with toiletpaper.remove(tp); 引发异常是因为您直接使用toiletpaper.remove(tp);修改了集合toiletpaper.remove(tp); . You have to use iter.remove() to modify the collection while iterating over it. 在迭代集合时,必须使用iter.remove()修改集合。

When you do the toiletpaper.remove(tp) you modify your linked list (you relink it) and therefore you get that error; 当您执行toiletpaper.remove(tp)您修改了链表(您将其重新链接),因此会收到该错误; your iterator is no longer valid. 您的迭代器不再有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM