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

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

问题描述

我有一个地图,要由几个线程同时修改。



在Java API中似乎有三种不同的同步Map实现:




  • Hashtable

  • Collections.synchronizedMap(Map)

  • ConcurrentHashMap



根据我的理解, Hashtable 是一个旧的实现(扩展过时的 Dictionary 类),后来已经适应 Map 界面。在同步时,似乎有严重可扩展性问题,并且不建议用于新项目。



但是其他两个呢? Collections.synchronizedMap(Map) ConcurrentHashMap 返回的地图之间有什么区别? c> ConcurrentHashMap c>

。它允许从几个线程并发修改映射,而不需要阻止它们。 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天全站免登陆