Possible Duplicate:
What’s the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?
I was reading differences between HashMap, Collenctions.synchonizedMap and ConcurrentHashMap. My understanding is that Collections.synchronizedMap applied lock on entire collection, hence performance overhead. But ConcurrentHashMap doesn't use synchronization. It uses segments to achieve the results, so it offers a similar performance as that of HashMap.
Please suggest if my understanding is correct. Also if this is the case, can I use ConcurrentHashMap everywhere even if there may not be multiple threads accessing it?
ConcurrentHashMap doesn't use synchronization. It uses segments to achieve the results
ConcurrentHashMap synchronizes at the segment level allowing atomic operation like putIfAbsent or replace old value with new value. The advantage is derived by a technique called lock-striping.
can I use ConcurrentHashMap everywhere even if there may not be multiple threads accessing it?
No, there's no reason that I can think of for doing that. Leaving performance apart, the choice of a data structure also serves as a documentation as to how the code is expected to be used (HashMap--> single thread). Use ConcurrentHashMap only when the class where it's being used is thread safe; otherwise the use of a thread safe data structure in a non thread safe class adds to the confusion of the next person looking at the code.
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