ConcurrentHashMap 的示例
我正在阅读文章“Java理论与实践:构建更好的HashMap” 很好地概述了 ConcurrentHashMap 的实现。
我还在 Stackoverflow 此处找到了一些关于它的讨论。
我的疑问是“使用 ConcurrentHashMap 的场景/应用程序/地点是什么”。
谢谢
I was reading the article "Java theory and practice: Building a better HashMap" that gives an excellent overview about the implementation of ConcurrentHashMap.
I also found some discussions over it on Stackoverflow here.
I question though I had in my mind is "what are the scenarios/applications/places" where ConcurrentHashMap is used.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在使用
HashMap
的相同实例中使用ConcurrentHashMap
,只不过您计划在多个线程上使用该映射。You would use a
ConcurrentHashMap
in the same instances you would use aHashMap
, except that you plan on more than one thread using the map.例如,我使用它来快速查找多线程服务器中的用户 ID 和用户对象。
我有一个网络线程、一个用于定期任务的计时器线程和一个用于处理控制台输入的线程。多个线程访问用户的哈希图,因此需要线程安全。
I use it for quick lookup from user ids to user objects in a multi-threaded server for instance.
I have a network-thread, a timer thread for periodical tasks and a thread for handling console input. Multiple threads access the hash map of users, thus it needs to be thread safe.
对于大型 Map 或大量读写操作,建议使用 ConcurrentHashMap ,因为:
考虑以下示例:
输出将是:
如您所见,对于
HashMap
,将抛出ConcurrentModificationException
因为您试图更改当前迭代的映射! (具体来说,异常将在语句上抛出:String key = itr1.next();
)Using
ConcurrentHashMap
is recommended for large Maps or large number of read-write operations due to:Consider the following example:
The output will be:
As you can see, for the
HashMap
aConcurrentModificationException
will be thrown because you trying to change a map that you currently iterating on! (specifically, the exception will be thrown on the statement :String key = itr1.next();
)