ConcurrentHashMap 和 Collections.synchronizedMap(Map) 有什么区别? [英] What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?
问题描述
我有一个要由多个线程同时修改的 Map.
I have a Map which is to be modified by several threads concurrently.
Java API 中似乎有三种不同的同步 Map 实现:
There seem to be three different synchronized Map implementations in the Java API:
哈希表
Collections.synchronizedMap(Map)
ConcurrentHashMap
据我了解,Hashtable
是一个旧的实现(扩展过时的 Dictionary
类),后来经过调整以适应 Map
界面.虽然它是同步的,但它似乎有严重的可扩展性问题,不鼓励用于新项目.
From what I understand, Hashtable
is an old implementation (extending the obsolete Dictionary
class), which has been adapted later to fit the Map
interface. While it is synchronized, it seems to have serious scalability issues and is discouraged for new projects.
那另外两个呢?Collections.synchronizedMap(Map)
和 ConcurrentHashMap
返回的 Map 有什么区别?哪种适合哪种情况?
But what about the other two? What are the differences between Maps returned by Collections.synchronizedMap(Map)
and ConcurrentHashMap
s? Which one fits which situation?
推荐答案
如果需要,请使用 ConcurrentHashMap
.它允许从多个线程并发修改 Map 而无需阻止它们.Collections.synchronizedMap(map)
创建一个阻塞 Map,这会降低性能,尽管确保一致性(如果使用得当).
For your needs, use ConcurrentHashMap
. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map)
creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).
如果需要保证数据一致性,并且每个线程都需要有最新的地图视图,请使用第二个选项.如果性能至关重要,则使用第一个,并且每个线程仅将数据插入到映射中,读取发生的频率较低.
Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.
这篇关于ConcurrentHashMap 和 Collections.synchronizedMap(Map) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!