Reputation: 10429
Iterators in Java are fail-fast. If an iterator values change while it is being iterated over, an exception is thrown.
Is this purely to be safe? I am sure that in some cases, it doesn't matter that much if the values change. For example, suppose you were sending non critical alerts to members in an iterator every 10 seconds - why would you care if the contents is changed?
Also, the fail-fast implementation just checks the count. This is flawed in case another thread adds and removes the count will be the same even though the iterator's contents is changed. Would be not be better to use a version number?
Upvotes: 0
Views: 81
Reputation: 72019
The fail-fast behavior is purely to aid debugging. The general rule is that if you modify a collection while iterating over it through some means other than the iterator's members, the behavior of the iterator is no longer predictable. It will throw an exception on a best-effort basis.
As such, any method of tracking that is expensive is a bad idea.
Upvotes: 1