ConcurrentHashMap vs ConcurrentSkipListMap clarification ConcurrentHashMap vs ConcurrentSkipListMap clarification multithreading multithreading

ConcurrentHashMap vs ConcurrentSkipListMap clarification


ConcurrentHashMap

Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.

it uses volatile semantics for get(key). In case when Thread1 calls put(key1, value1) and right after that Thread2 calls get(key1), Thread2 wouldn't wait Thread1 to finish its put, they are not synchronized with each other and Thread2 can get old associated value. But if put(key1, value1) was finished in Thread1 before Thread2 tries to get(key1) then Thread2 is guaranteed to get this update (value1).

ConcurrentSkipListMap is sorted and provides

expected average log(n) time cost for the containsKey, get, put and remove operations and their variants

ConcurrentSkipListMap isn't so fast, but is useful when you need sorted thread-safe map.


The API however goes on to suggest that it does not gaurantee locking for retrieval so you may get misleading results here?

Interestingly enough, neither does the ConcurrentSkipListMap, infact the CSLM is completely non-blocking.

In Java 7 The CHM, for all intents and purposes, is non-blocking when executing reads. In fact, Java 8's updated CHM implementation has completely non-blocking reads.

The point here is that the CHM and CSLM have similar read semantics, the difference is time complexity.


From your question, you seem to have come to the conclusion that only insertions into ConcurrentHashMap are thread safe.

From my understanding ConcurrentHashMap gaurantees thread safety for insertions by multiple threads. So if you have a map that will only be populated concurrently by multiple threads then there are no issues.

How did you come to this conclusion? The first line of the documentation for ConcurrentHashMap implies that all operations are thread safe:

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.

Additionally, it implies that get() operations can sustain a higher level of concurrency than put() operations.

Simply put ConcurrentHashMap does not have the retrieval issue that you think it has. In most cases you should be using ConcurrentHashMap instead of ConcurrentSkipListMap since performance of ConcurrentHashMap is generally better than ConcurrentSkipListMap. You should only be using CurrentSkipListMap when you need a ConcurrentMap that has predictable iteration order or if you need the facilities of a NavigableMap.