为什么 Java 不附带 CopyOnWriteMap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4241477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:27:56  来源:igfitidea点击:

Why doesn't Java ship with a CopyOnWriteMap?

javacollectionsmapconcurrencyconcurrenthashmap

提问by sgargan

The JDK ships with CopyOnWrite*implementations for Setand List, but none for Mapand 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?

JDK中附带了CopyOnWrite*用于实现SetList,但没有对Map和我常常感叹这个事实。我知道还有其他的集合实现有它们,但如果有一个作为标准交付会很好。这似乎是一个明显的遗漏,我想知道是否有充分的理由。任何人都知道为什么这被遗漏了?

采纳答案by Fredrik Bromee

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

我想这取决于您的用例,但是当您已经拥有ConcurrentHashMap时,为什么还需要 CopyOnWriteMap ?

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-freefashion.

等于写集合上的副本。多个读者可以以无方式同时从地图中检索元素。

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 dowant to have the effect of a copy on write map, you can always initialize a ConcurrentHashMap with a concurrency level of 1.

如果确实希望在写映射上具有副本的效果,则始终可以初始化并发级别为 1 的 ConcurrentHashMap。

回答by Ustaman Sangat

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].

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

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

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

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

但是正如您所看到的,CopyOnWriteArraySet实际上是由数组而不是映射支持的。而且不会Collections.newSetFromMap(ConcurrentHashMap的())为您的用例可以接受吗?