Re: Removing object from arraylist when pointed to by iterator
Lasse Reichstein Nielsen wrote:
And maybe you won't see a ConcurrentModificationException, but
that's because doing it that way won't notice the bugs you've
introduced by concurrent modifications.
That is correct, except in the case where you know, and I mean
*absolutely* know, that the list is only *ever* used in a single
thread.
Concurrent modification bugs do not require multiple threads to appear.
As a matter of fact, I've run into them most often in programs where
only one thread has access to the collection in question. Algorithms
like the following can lead to the bug:
1. Go through all SimulationObjects
2. execute doSomething on each object.
where the some SimulationObject instance have a doSomething that can
affect the list of all simulation objects. Such as a robot firing a
missile (addition), or a missile exploding and killing a robot
(removal). In that case, I might never have noticed the bug if I was
using get. As it turns out, the "best" way around that bug in my code
was to create a two lists "toBeRemoved" and "toBeAdded", and handle that
after the main loop.
So, the point remains, use Iterator, and if you get CME don't assume its
a synchronization/threading issue (although it might me).
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>