Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any drawbacks with ConcurrentHashMap?

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?

like image 321
Thilo Avatar asked Oct 17 '10 02:10

Thilo


3 Answers

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.

like image 92
Stephen C Avatar answered Nov 14 '22 06:11

Stephen C


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.

like image 41
andersoj Avatar answered Nov 14 '22 07:11

andersoj


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.

like image 2
sjlee Avatar answered Nov 14 '22 07:11

sjlee