I am reading the book Java Concurrecny in practice. On page 85 section 5.2.1 it talks about the ConcurrentHashMap and its advantages. However, in one part, the books claims that
the iterators returned by ConcurrentHashMap is weakly consistent. This
means that this iterator can tolerate concurrent modification,
traverses elements as they existed when iterator was constructed, and
may (but not guaranteed to) reflect modifications to the collection
after the construction of the iterator.
From why I understand the whole point of synchronization in concurrent programs is to allow thread accessing a shared resource in a consistent way, where as ConcurrentHashMap is not really fulfilling this. Then why using it at all?
The point is to avoid synchronization when you don’t need it. If you don’t mind seeing new elements in some cases and not seeing them in others, using
ConcurrentHashMap‘s iterator can be significantly cheaper than either preventing other threads from adding items while you’re iterating or taking a consistent snapshot when the iterator is created.So yes, when you need synchronization and a consistent iterator, you’ll need an alternative – but when you don’t, you can take advantage of the more efficient iterator provided by
ConcurrentHashMap.