Sign in to follow this  
CodeMachine

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

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this