Jump to content
  • Advertisement
Sign in to follow this  
CodeMachine

[java] Thread problem: "java.util.ConcurrentModificationException"

This topic is 4331 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello folks! I have an ArrayList, arr. To this arraylist, I add/remove items (by pressing Enter/Esc). In my thread, I loop through this arraylist and print out all the elements. But if I add/remove one item exactly while the thread is reading from the arraylist, I get the ConcurrentModificationException. How do I solve this? I think I should use "synchronized" somehow? I don't get it to work... Anyone? Kind Regards

Share this post


Link to post
Share on other sites
Advertisement
Wherever you are accessing the ArrayList do this (where theList is your ArrayList):

...
synchronized( theList )
{
//loop through the list
}
...

...
synchronized( theList )
{
//Add an element to the list
}
...

etc.

That way, only one section of code will be allowed to use the ArrayList at a time.

If responsiveness for adding and removing items is a priority, then you will have to clone the list in a sychronized block. After you have cloned the list, release the lock and print it out so adding & removing can continue elsewhere.

Cheers,
Brett

Share this post


Link to post
Share on other sites
Basically you can not add/remove when you are iterating over a collection that is not synchronized such as the ArrayList.

Share this post


Link to post
Share on other sites
Quote:
Original post by Son of Cain
You can use an Iterator instance to do the removal:


Iterator it = list.iterator();
while ( it.hasNext() ) {
it.remove();
}


But what happens if I try to "it.remove()" while my thread is reading the arraylist?

Share this post


Link to post
Share on other sites
You'll want to put a synchronized block around your iteration loop. E.g.

synchronized (list)
{
for (Iterator it = list.iterator(); it.hasNext();)
{
it.remove();
}
}
because modifying the list from another thread will invalidate the iterator.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!