🔒 Locked
[java] Thread problem: "java.util.ConcurrentModificationException"
Advertisement
Original Post
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
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
...
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
If I'm not mistaken, you can also create a synchronized List using a Collections' class method, synchronizedList().
Thanks dudes!
I'll take a look at these three answers...
I'll take a look at these three answers...
You can use an Iterator instance to do the removal:
Iterator it = list.iterator();while ( it.hasNext() ) { it.remove();}
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?
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.
Advertisement