问题描述
我读了一篇关于线程安全地图的文章并得到了一个问题。 Collections.synchronizedMap()
代理底层地图,在每个方法上添加 synchronized
块。另一方面, ConcurrentHashMap
不会在读/写操作上锁定整个映射。这意味着多线程系统中的所有操作都更快。
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.
那么现在使用 synchronizedMap()
有什么好处? ?我看到了唯一的:
So what are the benefits of using synchronizedMap()
nowadays? I see the only:
- 从java 1.2开始可用它(对于
对于CSS $ 1.5> ConcurrentHashMap
) - 可以存储可以为空的值(如果底层地图可以这样做)
是否有 synchronizedMap()
更好的任何其他情况?
Are there any other situations when synchronizedMap()
is better?
推荐答案
有与 Collections.synchronizedMap(map)
和 ConcurrentHashMap
相关的利弊。
synchronizedMap
在您希望数据一致性时非常有用。每个访问线程都有一个地图的更新视图,这是通过阻止地图来实现的,这反过来会降低它的性能。
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 map
时,c $ c>非常有用。由于它适用于 map
的分段/分区,因此几个线程同时工作。但是访问线程可能没有map的更新视图。其他优点是故障安全
。 ConcurrentHashMap
不允许空键或值。
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.
使用 ConcurrentHashMap
如果性能高度关注那么数据一致性。
Use ConcurrentHashMap
if performance is high concern then data consistency.
这篇关于如果有ConcurrentHashMap,为什么需要synchronizedMap()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!