avoid ConcurrentModificationException

edited May 2014 in How To...

I looked in some options, for now i use:

for (Object instance : (ArrayList<Object>)list.clone())  

This seems to work fine. I was wondering what you guys prefer to deal with a ConcurrentModificationException.


  • Start at the end of the list and move backwards.

    for (int i=list.size()-1; i>=0; i--) {
        someClass instance = list.get(i);
        if (instance.removeThis) {
  • edited May 2014

    Don't use remove() w/ a reference argument. It's über slow O(n) search!
    Prefer remove() by index value always!!! >:/

  • Thanks amnon, that's how i used to do stuff :) Because i was more worried about threading i didn't think about it. I prefer it your way, the reverse looping cause i think it will be a lot faster then make a clone of a list.

    However, i just tried and it did gave me a index out of bounds exception after a while. I try to get that again as we speak. It seems like that the change for it to happen is reaaallly small.

  • edited May 2014

    This is my backwards loop cookie-maker of mine:

    // forum.processing.org/two/discussion/4923/
    // avoid-concurrentmodificationexception
    final StringList words = new StringList(new String[] {
      "clankill3r", "GoToLoop", "ammon"
    for (int i = words.size(); i-- != 0;) {
      final String word = words.get(i);
      if (random(1) < .3)  words.remove(i);
      else println(word);
    println("\n" + words);
  • Take a look at this thread to know about Thread further: ;)

  • thanks man.

    I readed about the synchronized thing but i'm afraid i get fps drops by that. Is that assumption wrong? Thinking about it, it probably matters if i put it in the PApllet thread or in the other Thread.

  • "Is that assumption wrong?"
    Don't assume, measure! ;-)

    synchronize is indeed slower than no synch, but you must worry only if the slow down is significant for your usage.

  • I tried synchronize, damn it's slow :)

  • Just saying w/o showing how you're implementing it won't help! I-)

  • I already fixed it by not using synchronize :) (I hope so, i need to test it with a beamer and a webcam today if i'm right)

Sign In or Register to comment.