Are there any drawbacks with ConcurrentHashMap?

好久不见. 提交于 2021-02-19 01:31:55

问题


I need a HashMap that is accessible from multiple threads.

There are two simple options, using a normal HashMap and synchronizing on it or using a ConcurrentHashMap.

Since ConcurrentHashMap does not block on read operations it seems much better suited for my needs (almost exclusively reads, almost never updates). On the other hand, I expect very low concurrency anyway, so there should be no blocking (just the cost of managing the lock).

The Map will also be very small (under ten entries), if that makes a difference.

Compared to a regular HashMap, how much more costly are the read and write operations (I am assuming that they are)? Or is ConcurrentHashMap just always better when there might be even a moderate level of concurrent access, regardless of read/update ratio and size?


回答1:


On the other hand, I expect very low concurrency anyway, so there should be no blocking (just the cost of managing the lock).

The cost of acquiring and releasing an uncontend Java mutex (primitive lock) is miniscule. So if you believe that the probability of contention is very low then a simple HashMap is probably your best bet.

But this is all conjecture. Unless and until you have actually profiled your application, all time spent on speculative optimization is most likely (*) time wasted.

* ... unless you have a really good intuition.




回答2:


CHM pays some penalty for the use of Atomic* operations under the covers, when compared to HashMap. How much? Guess what... measure it in your app... ;-)

If you find that you actually have a performance problem, there's probably a very specialized solution for <10 entries that would be cheaper than any solution assembled out of java.util land, but I'd not jump to that until you know you have a performance issue.




回答3:


In terms of throughput and performance, the overhead is usually negligible.

On a different note, the memory footprint of a ConcurrentHashMap (at the instance level) is somewhat larger than a HashMap. If you have a large number of small-sized CHMs, this overhead might add up.




回答4:


The main issue w/ CHM: it doesn't scale well unless you change the c-tor call but mostly it doesn't automatically scale for the available cores.

3 links below to lock-free hashmap
http://www.azulsystems.com/blog/cliff-click/2007-03-26-non-blocking-hashtable
http://www.azulsystems.com/blog/cliff-click/2007-04-01-non-blocking-hashtable-part-2
http://sourceforge.net/projects/high-scale-lib/



来源:https://stackoverflow.com/questions/3951676/are-there-any-drawbacks-with-concurrenthashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!