java ConcurrentModificationException 即使同步 [英] java ConcurrentModificationException even with synchronized

查看:27
本文介绍了java ConcurrentModificationException 即使同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前已经发布过类似的问题,但这种情况有所不同 - 静态使用可能会使问题复杂化.只是想看看是否有人对如何处理这个问题有想法.即使我在修改它的两个块周围的列表上使用同步,我也得到了 ConcurrentModificationException.

Similar issue has been posted before but this case is different - there is static usage which may be the complicating it. Just want to see if anyone has ideas on how to handle this. I get the ConcurrentModificationException even though I am using synchronzed on the list around both blocks that modify it.

public class Foo {
   public void register() {
       FooManager.addFoo(this);
   }
}

public class ABC1 {
   static Foo myfoo;
   static {
     myfoo = new Foo();
     myfoo.register();
   }
}

(我有多个相似的类 ABC2、ABC3)

(I have mutliple similar classes ABC2, ABC3)

public class FooManager {
   static ArrayList<Foo> m_globalFoos;
   static ABC1 m_abc;
   static {
     m_globalFoos = new ArrayList<Foo>();
     m_abc = new ABC1();
   }


   public static void addFoo(Foo foo) {
     synchronized(m_globalFoos) { // SYNC
         m_globalFoos.add(foo);
      }
   }

    public static void showFoos() {
        synchronized(m_globalFoos) { //SYNC
            for (Foo foo : m_globalFoos) {
                     foo.print();
            }
    }
}

我声明超过 1 个线程函数中的 ABC1、ABC2、ABC3 等.在我的主程序中,第一行

I declare ABC1, ABC2, ABC3 etc in more than 1 thread func. In my main program, first line

main() {
    FooManager.showFoos();

异常详情:

Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
        at java.util.AbstractList$Itr.next(AbstractList.java:343)
        at com.mytest.FooManager.showFoos(FooManager.java:78)
        at com.mytest.FooTest.main(FooTest.java:109)

推荐答案

实际上,您的内在锁位于您正在迭代的 ArrayList 上.看起来 FooHandler 或 print() 函数都有一个对您的 ArrayList 的引用,它正在尝试向其中添加/删除内容.根据JAVADOC,这个异常可能是由于相同的线程或不同的线程而发生的,但并不总是不同的线程.因此,如果您有某种操作试图修改您的 Arraylist,则可能会发生此错误.

Actually, your intrinsic lock is on the ArrayList that you are iterating. Looks like either the FooHandler OR the print() function has a reference back to your ArrayList which is trying to add/remove content to it. According to JAVADOC, this exception can happen because of either the same thread or a different thread, but not always a different thread. So, if you have some kind of operation that is trying to modify your Arraylist, then this error can occur.

尝试使用快速失败迭代器来避免此类错误.

try to use fail-fast iterators for avoiding such errors.

这篇关于java ConcurrentModificationException 即使同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆