I'd like to clarify something about ConcurrentHashMap vs ConcurrentSkipListMap based on the API documentation.
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. The API however goes on to suggest that it does not gaurantee locking for retrieval so you may get misleading results here?
In contrast, for the ConcurrentSkipListMap it is stated that: "Insertion, removal, update, and access operations safely execute concurrently by multiple threads". So I assume this does not have the aforementioned retrieval issue that the hash map has, but obviously this would generally come with a performance cost?
In practice, has anyone found the need to use the ConcurrentSkipListMap because of this particular behaviour, or does it generally not matter that retrievals may give an out of date view?
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.