Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by CodeMachine Sep 27, 2006 at 1:28 PM 8 replies 28.6k views
Original Post
CodeMachine
CodeMachine
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
Shabadoo
Shabadoo
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
Son of Cain
Son of Cain
If I'm not mistaken, you can also create a synchronized List using a Collections' class method, synchronizedList().
a.k.a javabeats at yahoo.ca
LizardCPP
LizardCPP
You should look into and understand the need for the java.util.concurrent package.

Lizard
CodeMachine
CodeMachine
Thanks dudes!
I'll take a look at these three answers...
Paclaw
Paclaw
Basically you can not add/remove when you are iterating over a collection that is not synchronized such as the ArrayList.

Paclaw
Son of Cain
Son of Cain
You can use an Iterator instance to do the removal:

Iterator it = list.iterator();while ( it.hasNext() ) {  it.remove();}
a.k.a javabeats at yahoo.ca
Paclaw
Paclaw
and with a ListIterator you can add...
Paclaw
CodeMachine
CodeMachine
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?
lucky_monkey
lucky_monkey
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.