This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
While reading about difference of HashMap and HashTable I came across following statement.
Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
I could not understand that why should the exception be throw only when there is structural modification.
Naresh Chaurasia wrote:I could not understand that why should the exception be throw only when there is structural modification.
adding an element into a map/list when you iterate that doesnt make sense. elements are added to the list at the time of iterating the list which keeps the list grow, never end.
if it could not throw ConcurrentModificationException[fail-fast], it throw an OutOfMemoryException after many Iteration and operations which waste your and cpu time.
note:enumeration is not a fail-fast mechanism. so using an iterator or for-each is a good practice.
If I understand this correctly, error is thrown if the number of elements in the map changes (you either add or remove elements). It makes sense, because iterator coul then return an element that no longer exists in map or skip an element while passing trough the Hashmap.
The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.