Sobes.tech
Junior — Middle

Can you explain the differences between Fail-fast and Fail-safe approaches when working with collections in Java?

sobes.tech AI

Answer from AI

In Java, when working with collections, there are two approaches to handling modifications during iteration: Fail-fast and Fail-safe.

  • Fail-fast collections (e.g., ArrayList, HashMap) throw a ConcurrentModificationException upon detecting structural modifications (adding, removing elements) during iteration. This helps quickly identify errors related to concurrent modification of the collection.

  • Fail-safe collections (e.g., CopyOnWriteArrayList, ConcurrentHashMap) work with a copy of the data or use special synchronization mechanisms, so modifications during iteration do not lead to exceptions. The iterator of such collections does not reflect changes made after its creation.

Example:

List<String> list = new ArrayList<>();
list.add("a");
list.add("b");

for (String s : list) {
    list.add("c"); // will cause ConcurrentModificationException
}

In the case of CopyOnWriteArrayList:

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("a");
list.add("b");

for (String s : list) {
    list.add("c"); // will not cause an exception, iterator works with a copy
}

Thus, Fail-fast helps quickly detect errors, while Fail-safe ensures safety during concurrent access, but with some limitations regarding performance and data freshness.