Fail Safe vs Fail Fast Operations in Java - DevDummy

Latest

Views | Thoughts | Concepts | Techniques

Thursday, May 04, 2023

Fail Safe vs Fail Fast Operations in Java

 


Fail-safe and fail-fast operations in Java are related to the behavior of iterators when a collection is modified while it is being iterated.

A fail-safe iterator creates a copy of the collection and iterates over the copy, rather than the original collection. This ensures that the iterator does not throw a ConcurrentModificationException if the collection is modified during iteration. However, it can potentially cause performance issues due to the creation of a copy of the collection. Examples of fail-safe iterators include the iterators used by ConcurrentHashMap and CopyOnWriteArrayList.

Map<String, Integer> map = new ConcurrentHashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); Integer value = map.get(key); System.out.println(key + " = " + value); map.put("four", 4); // won't throw ConcurrentModificationException }

In this example, we are using a ConcurrentHashMap, which uses a fail-safe iterator. We add an element to the map during iteration, but the iterator does not throw a ConcurrentModificationException.

A fail-fast iterator, on the other hand, throws a ConcurrentModificationException if the collection is modified during iteration. This is because fail-fast iterators operate directly on the collection and detect any modifications made to the collection during iteration. Examples of fail-fast iterators include the iterators used by ArrayList, HashSet, and HashMap.

List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String value = iterator.next(); System.out.println(value); list.add("d"); // will throw ConcurrentModificationException }

In this example, we are using an ArrayList, which uses a fail-fast iterator. We add an element to the list during iteration, which causes the iterator to throw a ConcurrentModificationException.

References

  1. https://docs.oracle.com/javase/tutorial/essential/concurrency/collections.html