ConcurrentHashMap有什么缺点吗? [英] Are there any drawbacks with ConcurrentHashMap?

查看:485
本文介绍了ConcurrentHashMap有什么缺点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可以从多个线程访问的HashMap.

I need a HashMap that is accessible from multiple threads.

有两个简单的选项,使用普通的HashMap并对其进行同步,或者使用ConcurrentHashMap.

There are two simple options, using a normal HashMap and synchronizing on it or using a ConcurrentHashMap.

由于ConcurrentHashMap不会阻止读取操作,因此它似乎更适合我的需求(几乎只进行读取,几乎从不更新). 另一方面,我希望并发性非常低,因此应该没有阻塞(只是管理锁的成本).

Since ConcurrentHashMap does not block on read operations it seems much better suited for my needs (almost exclusively reads, almost never updates). On the other hand, I expect very low concurrency anyway, so there should be no blocking (just the cost of managing the lock).

如果有所不同的话,地图也将非常小(少于10个条目).

The Map will also be very small (under ten entries), if that makes a difference.

与常规的HashMap相比,读和写操作的成本要高多少(我假设是的)?还是在可能存在适度并发访问级别的情况下,无论读/更新比率和大小如何,ConcurrentHashMap总是总是更好?

Compared to a regular HashMap, how much more costly are the read and write operations (I am assuming that they are)? Or is ConcurrentHashMap just always better when there might be even a moderate level of concurrent access, regardless of read/update ratio and size?

推荐答案

另一方面,无论如何我期望并发性很低,因此应该没有阻塞(只是管理锁的成本).

On the other hand, I expect very low concurrency anyway, so there should be no blocking (just the cost of managing the lock).

获取和释放不受竞争的 Java互斥锁(原始锁)的成本很小.因此,如果您认为竞争的可能性很低,那么简单的HashMap可能是您的最佳选择.

The cost of acquiring and releasing an uncontend Java mutex (primitive lock) is miniscule. So if you believe that the probability of contention is very low then a simple HashMap is probably your best bet.

但这全是猜测.除非并且直到您实际配置了应用程序,否则所有用于推测性优化的时间都很可能浪费了(*)时间.

But this is all conjecture. Unless and until you have actually profiled your application, all time spent on speculative optimization is most likely (*) time wasted.

* ...除非您真的有 直觉.

* ... unless you have a really good intuition.

这篇关于ConcurrentHashMap有什么缺点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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