InterviewSolution
| 1. |
What is the situation in which fail-fast and fail-safe iterators works? What are the issues to use the fail-safe along with the example? |
|
Answer» Fail fast and fail-safe is one of the prominent features of collection iterator framework, which works on the principle of modification of a record in the collection object while iterating over it, HOWEVER, both have a different way to handle. Fail Fast iterator: The fail-fast iterator checks, If there is modification happening while iterating over the elements, it will check and throw the exception called a ConcurrentModificationException. Typically the fail-fast iterator implements the volatile counter whenever the iterator gets instantiated this counter embedded to the iterator and in the case of any modification it will increment the counter if it is greater than one it will throw the exception. Below is the code snippet for same. public class FailFastDemo{ public static void main(String[] args) { Map<String, String> capital = new HashMap<String, String>(); capital.put("Delhi", "INDIA"); capital.put("Moscow", "Russia"); capital.put("New YORK", "USA"); Iterator iterator = capital.keySet().iterator(); while (iterator.hasNext()) { System.out.println(capital.get(iterator.next())); // in this code we are modifying the element to Map // exception will be thrown on next call // of next() method. capital.put("Istanbul", "Turkey"); } } }Fail-safe Iterator: Fail safe iterator is a part of the java.util.concurrent api, it works on the principal of the CLONING, actually in this case it creates the clone of the object and iterate over it, if any modification happens, it wouldn’t touch to the actual object and continue to iterate without failure. One issue with the fail-safe iterator is, it doesn’t guarantee that updated elements will be reflected in the iteration. And another issue is it CONSUMES more memory than fail fast because it requires to create the clone, whereas failing fast works only original one. The CopyOnWriteArrayList and ConcurrentHashMap is the example of fail-safe iterator. Below is the code snippet for same. ConcurrentHashconcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashconcurrentHashMap<>(); concurrentHashMap.put("First", 10); concurrentHashMap.put("Second", 20); concurrentHashMap.put("Third", 30); concurrentHashMap.put("Fourth", 40); Iterator<String> iterator = concurrentHashMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); concurrentHashMap.put("Fifth", 50); } |
|