Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why need synchronizedMap() if there is ConcurrentHashMap? [duplicate]

I read an article about thread safe maps and got a question. Collections.synchronizedMap() proxies underlying map with adding synchronized blocks on each method. On the other hand ConcurrentHashMap doesn't lock the whole map on read/write operations. Which means all operations in multi thread system are faster.

So what are the benefits of using synchronizedMap() nowadays? I see the only:

  1. it's available since java 1.2 (vs java 1.5 for ConcurrentHashMap)
  2. can store nullable values (if underlying map can do it)

Are there any other situations when synchronizedMap() is better?

like image 843
awfun Avatar asked Oct 14 '25 03:10

awfun


2 Answers

There is pros and cons associated with both Collections.synchronizedMap(map) and ConcurrentHashMap.

synchronizedMap is useful when you want data consistency. Each accessing thread will have an update view of the map which is achieved by blocking the map which in turn degrades it performance.

ConcurrentHashMap is useful when you needs to modify map frequently. Since it works on segmentation/partition of map several thread work simultaneously on it. But there is possibility that an accessing thread might not have an update view of map. Other advantage is that it is fail-safe. ConcurrentHashMap does not allow null keys or values.

Use ConcurrentHashMapif performance is high concern then data consistency.

like image 164
Geek Avatar answered Oct 18 '25 03:10

Geek


Not really. The only other case I can think of is easily making a custom map implementation thread safe.

like image 28
Ede Avatar answered Oct 18 '25 04:10

Ede



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!