由于未同步的同步方法导致的ConcurrentModicationException

时间:2013-08-05 15:49:50

标签: java multithreading synchronization sync

我有一堆从基类启动的Runnable对象。这些对象在随机时间迭代并删除共享ArrayList中的项。我已经同步了两种方法,但我得到了ConcurrentModicationException。我相信它是因为they are synchronized but are not synchronized on each other。是这样的吗?如果是这样,我会获得锁定哪个类?

环境类:

class Environment{

     ArrayList<Critter> critter_array = new ArrayList<Critter>();
     ArrayList<Food> food_array = new ArrayList<Food>();

     Environment(){
         Executor ex = Executors.newCachedThreadPool(); 
         Critter A = new Critter();
         Critter B = new Critter();
         critter_array.add(A);
         critter_array.add(B);
         ex.execute(A); 
         ex.execute(B);
     }

     public synchronized void destroyFood(Food item){
         Iterator<Food> iter = food_array.iterator();
         while(iter.hasNext()){
             Food temp = iter.next();
             food_array.remove(temp);
             break;
         }      
     }

}

Critter class:

class Critter implements Runnable{
     Environment envi;

     Critter(Environment E){
          envi = E;
     }

     @Override
     public void run() {
         //do other stuff
         CritterUtilities.iteratorMethod(this, envi);
     }
}

CritterUtilities类:

class CritterUtilities{

    public static synchronized iteratorMethod(Critter self, Environment envi){
         Iterator<OtherObject> iter = envi.getFood().listIterator();
         while(iter.hasNext()){
             Food temp = iter.next();   /////////Problem is here
             //other stuff that's not related to the prob
        }
    }

}

堆栈追踪:

Exception in thread "pool-1-thread-2" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at CritterUtil.getViewableFood(CritterUtil.java:28)
at CritterUtil.getNearestFood(CritterUtil.java:41)
at Critter.hunt(Critter.java:163)
at Critter.run(Critter.java:139)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

2 个答案:

答案 0 :(得分:4)

错误并不一定会阻止多线程,而是在使用迭代器时从列表中删除项目:

 public synchronized void destroyFood(Food item){
     Iterator<Food> iter = food_array.iterator();
     while(iter.hasNext()){
         Food temp = iter.next();
         food_array.remove(temp); // <-- this is the problem
         break;
     }      
 }

相反,请使用Iterator.remove()方法:

 public synchronized void destroyFood(Food item){
     Iterator<Food> iter = food_array.iterator();
     while(iter.hasNext()){
         iter.remove(); // <-- this is how you remove elements while iterating
         break;
     }      
 }

另一方面,您的同步 错误。您的每个synchronized方法都在同步另一个对象。为了让它们在同一个对象上进行所有同步,最简单的方法就是让它们在列表本身上同步。

答案 1 :(得分:1)

除了DaoWen发现的错误删除外,同步也是错误的。 iteratorMethod()destroyFood()不使用相同的对象进行同步。目前,他们使用各自的对象进行同步。它应该是这样的:

 public void destroyFood(Food item) {
     synchronized (food_array) {
         // ... proceed with the removal
     }
 }

public static iteratorMethod(Critter self, Environment envi){
    List<OtherObject> list = envi.getFood();
    synchronized (list) {
        // the rest of iteratorMethod should go here
    }
}

(我假设getFood()返回食物数组,因此对象将是相同的。)

同样的修复应该应用于修改或迭代食物清单的任何其他方法。