Fail fast

Using rapid collection of container failure mechanism, using iterators to traverse a collection, in addition to the iterator own remove () method, any other way of structural changes, the collection will throw ConcurrentModificationException.

The collection classes in the java.util package are designed to fail fast and cannot be modified concurrently (iteratively) in multiple threads.

The principle of

The iterator accesses the contents of the collection directly during traversal, so the contents of the collection cannot be modified during traversal. To protect against modification, iterators maintain a modCount variable that changes the value of modCount when the collection structure changes (adding, deleting, or modifying). Whenever the iterator iterates over the next element using the hasNext() and next() methods, it checks whether the modCount value is equal to the expectedmodCount value, and when modCount! = expectedmodCount, throw ConcurrentModificationException, vice continue to traverse.

Note: The fast failure mechanism of iterators is not guaranteed, where exceptions are thrown if modCount! = expectedmodCount This condition. If the modCount value is exactly equal to the expectedmodCount value when the set changes, the exception will not be thrown. Therefore, it would be a mistake to write a program that relies on this exception to improve the accuracy of such iterators; the iterator’s fast failure mechanism should only be used to detect bugs.

The advantages and disadvantages

  • The efficiency is relatively high in a single thread.
  • In multi-threaded environment, threads are not safe.

HashTable is excluded here.

Safety failure

For a collection container with a security failure mechanism, iterators are not used to access the contents of the collection directly, but to copy the contents of the original collection and traverse the copied collection.

The principle of

Iterators in traversed access is a copy of the collection, so in the process of traversing the changes to the original collection and cannot be detected by the iterator, so will not trigger a ConcurrentModificationException anomalies.

The advantages and disadvantages

  • Due to the collection for the copy, to avoid the abnormal ConcurrentModificationException, but copy generated when a large number of invalid object, overhead.
  • There is no guarantee that the data read is the latest data in the original set, that is, the iterator traverses the copied set, and the iterator cannot detect the changes in the original set during traversal.

Special instructions

Structural changes: Changes that change the size of the collection.

Non-structural changes: Changes that do not involve collection sizes.

The term “modification” in this article refers to “structural modification”. That is, if you just change the contents of the elements themselves in the collection, you won’t trigger the fast fail mechanism.