2

I'm researching about iterator invalidation rules in Java, but I couldn't find proper information like this one for C++. All things that I found for java is more generic like this one. Is there a documentation that I could follow?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
wonder
  • 31
  • 3

1 Answers1

1

Java "Collections Framework Overview" documentation says

The general-purpose implementations support all of the optional operations in the collection interfaces and have no restrictions on the elements they may contain. They are unsynchronized, but the Collections class contains static factories called synchronization wrappers that can be used to add synchronization to many unsynchronized collections. All of the new implementations have fail-fast iterators, which detect invalid concurrent modification, and fail quickly and cleanly (rather than behaving erratically).

Java has concurrent thread safe collections implementations. They are part of java.util.concurrent package, which doc says

Most concurrent Collection implementations (including most Queues) also differ from the usual java.util conventions in that their Iterators and Spliterators provide weakly consistent rather than fast-fail traversal:

  • they may proceed concurrently with other operations
  • they will never throw ConcurrentModificationException
  • they are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction.

For example for ConcurrentHashMap

Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time. Bear in mind that the results of aggregate status methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads. Otherwise the results of these methods reflect transient states that may be adequate for monitoring or estimation purposes, but not for program control.

So the short answer is: if you want to iterate the collection while it may change by another thread, just use concurrent implementation collections. This java iterator is never invalidated in "C++ meaning"

Or just use thread-unsafe collections and catch ConcurrentModificationException for fixing the collection modification issue. In this case, java iterator also is never invalidated in "C++ meaning".

Vitalii
  • 431
  • 4
  • 11