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:
ConcurrentHashMap
)Are there any other situations when synchronizedMap()
is better?
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 ConcurrentHashMap
if performance is high concern then data consistency.
Not really. The only other case I can think of is easily making a custom map implementation thread safe.
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