Difference between fail-fast and fail-safe - Java @ Desk

Monday, April 27, 2015

Difference between fail-fast and fail-safe

Difference between fail-fast and fail-safe

fail-fast and fail-safe are related to java.util.Iterator class in Java.

Iterator fail-fast states that, it should throw the exception ConcurrentModificationException if the collection is modified during the iteration. All the collection in java.util package are by default fail-fast in nature.

The exception is thrown as shown below
while(iterator.hasNext()) {
 iterator.next(); // It will throw ConcurrentModificationException once it reach here after adding an   element in the list

As shown above, next() throws the ConcurrentModificationException if the element is added in the list while iteration.

Iterator fail-safe states that, it will not throw ConcurrentModificationException even though the collection gets modified. Classes in the package java.util.concurrent are fail-safe. ConcurrentHashMap and CopyOnWriteArrayList are fail-safe because the iterator does not throws any exception while the collection gets modified. Click here for implementation of CopyOnWriteArrayList.

No comments:

Post a Comment