| 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.
|
 |
 |
|
|
subject: Collections#synchronizedList - what am I doing wrong?
|
|
|