The Java Concurrency in Practice mentions that:
The iterator returned by the
ConcurrentHashMap
are weakly consistent than fail-fast. A weakly consistent iterator can tolerate the concurrent modifications, traverses elements as they existed when the iterator was constructed, and may (but is not guaranteed to) reflect modifications to the collection after the construction of the iterator.
ConcurrentHashMap
will be modified. The only thing is that it'll not throw the ConcurrentModificationException
.Please keep in mind that Fail Fast iterator iterates over the original collection.
In contrast Fail Safe (a.k.a weakly consistent) iterator iterates over a copy of the original collection. Therefore any changes to the original collection go unnoticed, and that's how it guarantees lack of ConcurrentModificationException
s.
To answer your questions:
As you can see it's a trade-off between correctness of your use case and speed.
ConcurrentHashMap
(CHM) exploits multiple tricks in order to increase concurrency of access.
MapEntry
gets stored in one of the number of segments each itself being a hashtable which can be concurrently read (read
methods do not block).concurrencyLevel
(default 16). The number of segments determines the number of concurrent writers across the whole of the data. The equal spread of entries between the segments is ensured by additional internal hashing algorithm.HashMapEntry
s value is volatile
thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update