Re: cloning Iterators?
Andreas Leitgeb wrote:
Mike Schilling <mscottschilling@hotmail.com> wrote:
It seems safe enough to clone readonly iterators. Cloning iterators
that can modify the underlying Collection is asking for trouble; as
soon as one does, the others start throwing
ConcurrentModificationExceptions.
Owen hit the Nail on its head in his followup.
Anyway, there can *usually* be more than one iterator for
the same structure (except for those pointed out by Owen),
so it shouldn't make a difference to reading iterators,
whether a *cloned* iterator writes, or if a *normally obtained*
iterator writes.
At least, wherever more than one iterator can be created,
it would theoretically be also safe to clone them.
Anyone, who can falsify even this weakened thesis? :-)
Even Iterators that have not modified their underlying Iterable can throw
ConcurrentModificationException if another iterator, or anything else,
modifies the Iterable.
The iterators returned by this class's iterator and listIterator methods are fail-fast:
if the list is structurally modified at any time after the iterator is created,
in any way except through the iterator's own remove or add methods, the iterator will
throw a ConcurrentModificationException. Thus, in the face of concurrent modification,
the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic
behavior at an undetermined time in the future.
from <http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html>
but it applies to others, too.
So if you cloned an Iterator and the clone modified the underlying Iterable,
the original Iterator will throw a ConcurrentModificationException.
This suggests that CloneableIterators must not be "fail-fast". It also
suggests that classes such as ArrayList that do have fail-fast Iterators
cannot be retrofitted with CloneableIterators, or they will break documented
behavior.
--
Lew