7

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?

Community
  • 1
  • 1
mehta
  • 735
  • 1
  • 11
  • 26
  • I went through that question as well. It mostly talks about cases where multiple threads are involved and concurrency is required. However, I want to understand if I can use ConcurrentHashMap even where I had to use HashMap only. – mehta Jan 09 '13 at 05:50
  • You could .... but why would you? You're adding overhead for no reason; "similar" != "the same". – Brian Roach Jan 09 '13 at 05:50
  • 3
    In that case, you can take a look at http://stackoverflow.com/questions/1378310/performance-concurrenthashmap-vs-hashmap – Swapnil Jan 09 '13 at 05:51

1 Answers1

9

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.

Scorpion
  • 3,938
  • 24
  • 37