File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections#synchronizedList - what am I doing wrong?

 
Stephen Neal
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just answered my own question. Because its executing within the synchronized block.
 
shishir guptaa
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply but you have misunderstood my query.

As per my previous post I have found the answer.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic