Are there any drawbacks with ConcurrentHashMap?

Thilo picture Thilo · Oct 17, 2010 · Viewed 9.3k times · Source

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?

Answer

Stephen C picture Stephen C · Oct 17, 2010

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.