This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Collections#synchronizedList - what am I doing wrong? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Collections#synchronizedList - what am I doing wrong?" Watch "Collections#synchronizedList - what am I doing wrong?" New topic
Author

Collections#synchronizedList - what am I doing wrong?

Stephen Neal
Greenhorn

Joined: Jan 23, 2013
Posts: 3
Can someone tell me why the code below throws a ConcurrentModificationException (at least under Java 6)? It was my understanding that because the code takes a lock on the synchronized list prior to iterating the remove inside that block should not be allowed but when I run this it is (and the print out shows 2 items in the list) and the next iteration then throws a ConcurrentModificationException.

There are two flavours, one using the for loop and one with an iterator. Both produce the same result. I am scratching my head here. I would expected a deadlock which itself is not desirable but at this stage I am just confused about the remove being allowed.

Stephen Neal
Greenhorn

Joined: Jan 23, 2013
Posts: 3
Just answered my own question. Because its executing within the synchronized block.
shishir guptaa
Greenhorn

Joined: Dec 23, 2010
Posts: 3
what i can see the problem is

list.remove(o);

You should always use iterator to modify the list, like as below

ListIterator itr = list.listIterator();

while(itr.hasNext()){
iitr.remove();
System.out.println(list.size());
}

This will work for you.
Stephen Neal
Greenhorn

Joined: Jan 23, 2013
Posts: 3
Thanks for the reply but you have misunderstood my query.

As per my previous post I have found the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections#synchronizedList - what am I doing wrong?
 
Similar Threads
Iterator Pattern
ArrayList vs java.awt.List
Producer-Consumer
How to remove common item between 2 ArrayList