ConcurrentHashMap返回一个弱一致的迭代器,为什么我们应该使用它? [英] ConcurrentHashMap returns a weakly consistent iterator, why should we use it anyhow?

查看:765
本文介绍了ConcurrentHashMap返回一个弱一致的迭代器,为什么我们应该使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读Java Concurrecny这本书。在第85页第5.2.1节中,它讨论了ConcurrentHashMap及其优点。然而,在一部分中,书籍声称ConcurrentHashMap返回的迭代器的弱一致性

I am reading the book Java Concurrecny in practice. On page 85 section 5.2.1 it talks about the ConcurrentHashMap and its advantages. However, in one part, the books claims that


。这个
意味着这个迭代器可以容忍并发修改,
遍历元素,因为它们在构造迭代器时存在,并且
可以(但不能保证)反映对集合
的修改构造迭代器。

the iterators returned by ConcurrentHashMap is weakly consistent. This means that this iterator can tolerate concurrent modification, traverses elements as they existed when iterator was constructed, and may (but not guaranteed to) reflect modifications to the collection after the construction of the iterator.

为什么我理解并发程序中的整个同步点是允许线程访问共享资源一个一致的方式,其中ConcurrentHashMap不是真正实现这一点。那么为什么使用它呢?

From why I understand the whole point of synchronization in concurrent programs is to allow thread accessing a shared resource in a consistent way, where as ConcurrentHashMap is not really fulfilling this. Then why using it at all?

推荐答案

关键是当你不需要时,避免同步。如果你不介意在某些情况下看到新元素,而在其他情况下看不到它们,那么使用 ConcurrentHashMap 的迭代器可以明显比

The point is to avoid synchronization when you don't need it. If you don't mind seeing new elements in some cases and not seeing them in others, using ConcurrentHashMap's iterator can be significantly cheaper than either preventing other threads from adding items while you're iterating or taking a consistent snapshot when the iterator is created.

当您需要时,可以阻止其他线程添加项目同步和一致的迭代器,你需要一个替代 - 但是当你没有时,你可以利用 ConcurrentHashMap 提供的更高效的迭代器。

So yes, when you need synchronization and a consistent iterator, you'll need an alternative - but when you don't, you can take advantage of the more efficient iterator provided by ConcurrentHashMap.

这篇关于ConcurrentHashMap返回一个弱一致的迭代器,为什么我们应该使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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