为什么 Java 不附带 CopyOnWriteMap?

发布于 2024-10-03 16:04:01 字数 193 浏览 0 评论 0原文

JDK 附带了 SetListCopyOnWrite* 实现,但没有 Map 的实现,我经常感叹这个事实。我知道还有其他集合实现也有它们,但如果有一个作为标准提供,那就太好了。这似乎是一个明显的遗漏,我想知道是否有充分的理由。有人知道为什么这个被遗漏了吗?

The JDK ships with CopyOnWrite* implementations for Set and List, but none for Map and I've often lamented this fact. I know there are other collections implementations out there that have them, but it would be nice if one shipped as standard. It seems like an obvious omission and I'm wondering if there was a good reason for it. Anyone any idea why this was left out?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七堇年 2024-10-10 16:04:01

我想这取决于您的用例,但是当您已经拥有 ConcurrentHashMap

对于具有许多读者且只有一个或几个更新的普通查找表来说,它是一个很好的选择。

与写时复制集合相比:

读取并发性

等于写时复制集合。多个读取器可以以无锁方式同时从地图中检索元素。

写入并发性:

比基本上序列化更新(一次一个更新)的写入时复制集合具有更好的并发性。使用并发哈希映射,您很有可能同时进行多个更新。如果你的哈希键是均匀分布的。

如果您确实想要在写映射上实现复制的效果,则始终可以初始化并发级别为 1 的 ConcurrentHashMap。

I guess this depends on your use case, but why would you need a CopyOnWriteMap when you already have a ConcurrentHashMap?

For a plain lookup table with many readers and only one or few updates it is a good fit.

Compared to a copy on write collection:

Read concurrency:

Equal to a copy on write collection. Several readers can retrieve elements from the map concurrently in a lock-free fashion.

Write concurrency:

Better concurrency than the copy on write collections that basically serialize updates (one update at a time). Using a concurrent hash map you have a good chance of doing several updates concurrently. If your hash keys are evenly distributed.

If you do want to have the effect of a copy on write map, you can always initialize a ConcurrentHashMap with a concurrency level of 1.

弥繁 2024-10-10 16:04:01

集合最简单的实现通常是使用底层映射。他们甚至有一个 Collections.newSetFromMap() 方法 [可能仅从 1.6 开始]。

他们应该做的是拥有一个 CopyOnWriteMap 和 CopyOnWriteSet 相当于 Collections.newSetFromMap(new CopyOnWriteMap())。

但正如您所看到的,CopyOnWriteArraySet 实际上是由数组而不是映射支持的。 Collections.newSetFromMap(ConcurrentHashMap()) 不适合您的用例吗?

The easiest implementation of a set would usually be to use an underlying map. They even have a Collections.newSetFromMap() method [maybe from 1.6 only].

What they should have done was have a CopyOnWriteMap and the CopyOnWriteSet being equivalent to Collections.newSetFromMap(new CopyOnWriteMap()).

But as you can see the CopyOnWriteArraySet is actually backed by an array not a map. And wouldn't Collections.newSetFromMap(ConcurrentHashMap()) be acceptable for your usecase?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文