2

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That could be the issue. Or it could be the loop over the breeder strains. But synchronizing the access won't change anything unless all the threads do the same thing every time they access the collection. It should be encapsulated inside a class.
I tried synchronizing the breedes acces, but no help.. The exception is fired here "for (Breeder b : breeders)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.