问题描述
我有一个地图要同时被多个线程修改。Java API中似乎有三个不同的同步Map实现:
-
Hashtable
-
Collections.synchronizedMap(Map)
-
ConcurrentHashMap
根据我的理解, Hashtable
是一个旧的实现(扩展了过时的字典
类),它稍后修改为适合地图
界面。虽然 同步,但似乎有严重的,并且不鼓励新的项目。
但是另外两个呢?地图由 Collections.synchronizedMap(Map)
和 ConcurrentHashMap
之间的区别是什么?
根据您的需要,使用 ConcurrentHashMap
。它允许从多个线程并行修改Map,而不需要阻止它们。 Collections.synchronizedMap(map)
创建一个阻止地图,这会降低性能,尽管确保一致性(如果正确使用)。
如果需要确保数据一致性,请使用第二个选项,并且每个线程需要具有地图的最新视图。如果性能至关重要,则使用第一个,每个线程只会将数据插入到地图中,读取次数不太频繁。
I have a Map which is to be modified by several threads concurrently.
There seem to be three different synchronized Map implementations in the Java API:
Hashtable
Collections.synchronizedMap(Map)
ConcurrentHashMap
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.
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?
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)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!