Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use ConcurrentHashMap [duplicate]

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?

like image 272
mehta Avatar asked Jan 09 '13 05:01

mehta


1 Answers

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.

like image 89
Scorpion Avatar answered Sep 21 '22 00:09

Scorpion