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?
ConcurrentHashMap allows performing concurrent read and write operation. Hence, performance is relatively better than the Synchronized Map. In Synchronized HashMap, multiple threads can not access the map concurrently. Hence, the performance is relatively less than the ConcurrentHashMap.
The ConcurrentSkipListMap is a scalable implementation of ConcurrentNavigableMap. All the elements are sorted based on natural ordering or by the Comparator passed during it's construction time.
A ConcurrentHashMap is a thread-safe version of a HashMap that allows concurrent read and thread-safe update operation.
You should use ConcurrentHashMap when you need very high concurrency in your project. It is thread safe without synchronizing the whole map . Reads can happen very fast while write is done with a lock. There is no locking at the object level.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With