Search code examples
javaandroidcollectionsiterationconcurrentmodification

ConcurrentModificationException in a loop


I'm running this code on a separate Thread (not the UI Thread)

strains = new ArrayList<Strain>();
for (Breeder b : breeders) {
   for (Strain s : b.getStrains()) {
        strains.add(s);
    }
}

It sometime causes ConcurrentModificationException. I know that i can't add or remove object from a Collection that i'm iterating, but in this snippet I'm not iterating on strains. Where i'm wrong? Thanks


Solution

  • Synchronize your access. This kind of freezes the current breeder object, so that it will not be modified in any other thread. Methods that try to do this will be blocked. Blocked means that they just wait (like System.sleep(x)), until the synchronized block in the other thread has been processed.

    synchronized(breeders) {
        for (Breeder b : breeders) {
           for (Strain s : b.getStrains()) {
                strains.add(s);
            }
        }
    }
    

    Make sure that you also put synchronized around the other threads' access to breeders.