Question 7 : What do you understand by iterator fail-fast property?
Fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. ( Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection ).
Fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.
Question 8 : What is difference between fail-fast and fail-safe?
Fail-safe iterators are just opposite to fail-fast.
They never fail if you modify the underlying collection on which they are iterating, because they work on clone of Collection instead of original collection and that’s why they are called as fail-safe iterator.
Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException
Question 9 : How to avoid ConcurrentModificationException while iterating a collection?
You should first try to find another alternative iterator which are fail-safe.
For example if you are using List and you can use ListIterator.
If it is legacy collection, you can use enumeration.
If above options are not possible then you can use one of three changes:
If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.
You can convert the list to an array and then iterate on the array.
You can lock the list while iterating by putting it in a synchronized block.
Note that last two approaches will cause a performance hit.
Question 20 : What is the Difference between the Iterator and ListIterator?
- Iterator : Iterator Can Only get Data From forward Direction .
- ListIterator : An iterator for lists that allows one to traverse the list in either direction.modify the list during iteration, and obtain the iterator’s current position in the list.
Read full article from Java Collections Tricky Interview Questions And Answers
No comments:
Post a Comment