Thinker
Thinker

Reputation: 6892

Is iterator of HashMap fail-safe?

I was reading a properties of HashMap. And found an answer on SO having lot of votes which says:

Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not.

While the JavaDoc says

The iterators returned by all of this class's "collection view methods" are fail-fast:

Actually the number of votes on that answered has confused me. Else I think it is fail-fast only.

Can someone explain?

Upvotes: 2

Views: 5007

Answers (5)

festony
festony

Reputation: 71

Well I was confused by this as well, but actually it is very simple:

Say we have:

Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
HashMap<String, Integer> hm = new HashMap<String, Integer>();

Then for hm we can do hm.keySet().iterator() which returns an iterator and is fast-fail; while for ht, we can both do ht.keySet().iterator which returns an iterator and is fast-fail, and do ht.keys() which returns an enumeration object and is NOT fast-fail.

Upvotes: 0

Holger
Holger

Reputation: 298263

A lot of readers react on what they expect to read and overlook small discrepancies. The answer you linked actually explains the meaning of fail-fast so it’s only a single word that does not match there: “fail-safe” vs. “fail-fast”.

The other point is that a lot of people accept answers sounding plausible. I guess, no one has really tested whether Hashtable’s enumerator really behaves differently than HashMap’s iterator. Both attempt to fail-fast as of version 1.6.0_35 I just checked.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718946

I think it is fail-fast only.

You are correct. The person who wrote that Answer probably doesn't understand the difference between fail-fast and fail-safe.

Actually the number of votes on that answered has confused me.

Lots of votes doesn't necessarily mean that an SO Answer is correct. I spotted a couple of other problems with that Answer as well. IMO, it does NOT deserve the large number of upvotes that it has received.

Unfortunately, people vote for Answers for a variety of reasons, which can lead to all sorts of anomalies.

Upvotes: 1

upog
upog

Reputation: 5531

Iterator of HashMap is fail-fast It will throw an ConcurrentModificationException if you try to modify while iterating over it, while collection which come under "java.util.concurrent" package have fail-safe iterator. you can modify the collection while iterating over it. Mainly used in Multi threaded environment

Upvotes: 2

rocketboy
rocketboy

Reputation: 9741

Yes, your understanding is correct.

Fail-fast: Fail asap by making checks aggressively. HashMap's iterator is fail-fast because it throws a ConcurrentModificationException as soon as it detects change in underlying structure.

Upvotes: 1

Related Questions