2

I got a ConcurrentModificationExeption in what I thought to be a single thread case. I also know that if you iterate through a List and try to modify it in the loop, you would have an exception. Hence I actually iterate and modify it using an iterator. However, I still have the exception.

Basically, I am implementing some animation manager, and I store all my IAnimation objects in an ArrayList. There is one public method that changes the list, which is addAnimation. THere is another method that loops through the list, which is calculateTick. Since both methods are synchronized, I dont think I have a threading problem. And as mentioned earlier, I iterate thruogh the loop using the iterator. Do you guys have any ideas why I have this exception?

Here is my code:

    private List<IAnimation> animations = new ArrayList<IAnimation>();
    public synchronized void addAnimation(IAnimation animation) {
    animations.add(animation);
    mLooper.update();
    inAnimation = true;
}

public synchronized void calculateTick(float tpf) {     
    for (Iterator<IAnimation> iterator = animations.iterator(); iterator.hasNext();) {
        IAnimation animation= iterator.next();
                    boolean animateMore = animation.calculateTick(tpf);
        if (!animateMore ) {{
            iterator.remove();
        }
    }

}

And here is my exception:

 E/AndroidHarness(9546): Exception thrown in Thread[GLThread 1260,5,main]

04-17 11:55:38.001: E/AndroidHarness(9546): java.util.ConcurrentModificationException 04-17 11:55:38.001: E/AndroidHarness(9546): at java.util.ArrayList$ArrayListIterator.remove(ArrayList.java:582) 04-17 11:55:38.001: E/AndroidHarness(9546): at com.avaya.mco.gui.animation.AnimationManager.calculateTick(AnimationManager.java:50) 04-17 11:55:38.001: E/AndroidHarness(9546): at com.avaya.mco.gui.jmonkey.android.MyApplication.simpleUpdate(MyApplication.java:60) 04-17 11:55:38.001: E/AndroidHarness(9546): at ......

4

1 回答 1

0

are you sure there is no other function missing here that iterates over the list ? maybe something that plays the animation?

also, if that doesn't help , try using "ConcurrentLinkedQueue" : http://developer.android.com/reference/java/util/concurrent/ConcurrentLinkedQueue.html it's available to all versions , and it says that for the iterator : "...The returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction."

于 2012-04-21T22:14:01.057 回答