Fail-fast and fail-safe behavior in Java

Fail-fast behavior means that when an error or condition occurs that can lead to an error, the system immediately stops further work and notifies about it. Using a fail-fast approach avoids non-deterministic program behavior over time.

In the Java Collections API, some iterators behave like fail-fast and throw a ConcurrentModificationException if the collection was modified after it was created, i.e. added or removed an item directly from the collection, rather than using iterator methods.

This behavior is implemented by counting the number of modifications to the collection (modification count):

  • when the collection changes, the modification counter also changes;
  • when creating an iterator, the current value of the counter is passed to it;
  • each time the iterator is accessed, the stored counter value is compared with the current one, and if they do not match, an exception is thrown.

Difference between fail-fast and fail-safe

In contrast to fail-fast, fail-safe iterators do not throw any exceptions when the structure changes, because they operate on a clone of the collection instead of the original.

The CopyOnWriteArrayList iterator and the keySet view iterator of the ConcurrentHashMap collection are examples of fail-safe iterators.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed