ConcurrentHashMap和Collections.synchronizedMap(Map)有什么区别? [英] What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

查看:111
本文介绍了ConcurrentHashMap和Collections.synchronizedMap(Map)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图要同时被多个线程修改。



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 ConcurrentHashMaps? 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)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆