kaetzacoatl
kaetzacoatl

Reputation: 1469

Is Hashtable.entrySet() thread safe?

Is it safe to iterate over the set returned by Hashtable.entrySet()? What about Hashtable.values() and Hashtable.keySet()?

What I intent to do: I want update the entries of a Hastable while the table is used by different other threads. For this I have to iterate over all entries currently in the map. It's not important if any entries added/removed from other threads during the iteration are handled or not. Synchronizing on the Hashtable is not an option because the update may take to long.

Upvotes: 1

Views: 1106

Answers (3)

MikeFHay
MikeFHay

Reputation: 9013

No, iterating over the views of a Hashtable is not safe in the face of concurrent modification. From the javadoc (emphasis mine):

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, 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. The Enumerations returned by Hashtable's keys and elements methods are not fail-fast.

jabu.10245 is correct that a ConcurrentHashMap is more appropriate, and does meet your requirement of allowing iteration while concurrent modification is occurring.

Upvotes: 2

markspace
markspace

Reputation: 11030

I think we're just going to quote the documentation of Hashtable at you.

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.

I think the docs say it all: You can't depend on the iterator telling you when you've modified a Hashtable incorrectly. Either synchronize on the Hashtable, or use a different class.

Upvotes: 0

jabu.10245
jabu.10245

Reputation: 1892

From the JavaDoc:

Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

Better use a ConcurrentHashMap.

Upvotes: 3

Related Questions