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 sharedQueue.add(10); }
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