1

If you create your own Iterable container class and retrieve a java.util.Iterator over its elements, is there any coding pattern according to which any further additions of elements in the container should not be accessible from the Iterator? I'm thinking "no way, absolutely not, in fact the Iterator should be able to loop through all of the elements regardless of additions."

Or is it perhaps the case that a fail-fast Iterator should throw an Exception if next() is called after a new addition is made?

Been a while since I've coded in Java yet something stinks here.

Jason
  • 2,495
  • 4
  • 26
  • 37
  • 1
    The second is true. I believe if you try and do that with any of Java's inbuilt `Iterable`s you'll get a [ConcurrentModificationException](https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html) – Michael Mar 24 '17 at 15:01
  • You are most definitely correct in that, I looked up some of my older code and this is exactly what I ought to do. I wish you had answered this formally so I could accept it as an answer. This I now consider solved. – Jason Mar 24 '17 at 15:03
  • Done! Happy to help. – Michael Mar 24 '17 at 15:06

2 Answers2

2

Is it perhaps the case that a fail-fast Iterator should throw an Exception if next() is called after a new addition is made?

Correct. I believe if you try and do that with any of Java's inbuilt Iterables you'll get a ConcurrentModificationException

The entire Javadoc for that exception is worth a read regarding this. It's very concise. Rather than quote the whole thing, the salient point is that iterators which do not fail fast "[risk] arbitrary, non-deterministic behavior at an undetermined time in the future."

Michael
  • 41,989
  • 11
  • 82
  • 128
0

User Michael answered my question in the comment above. Fail-fast Iterators should do exactly the latter. Now when one should prefer Fail-fast over Fail-safe, I'm not sure, but given that containers are mutable by definition, I believe Fail-Fast might be the only way to go.

Jason
  • 2,495
  • 4
  • 26
  • 37
  • Fail-safe iterators have their usages but fail-fast is often preferable. Fail-safe iterators are okay provided copying the collection is not a problem (which it may be for large datasets) and you don't care whether the data you have is the most recent. – Michael Mar 24 '17 at 15:22