本文介绍了为什么没有针对 ConcurrentHashMap 的 ConcurrentHashSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashSet 基于 HashMap.

HashSet is based on HashMap.

如果我们看看 HashSet 的实现,一切都在 HashMap 下进行管理.

If we look at HashSet<E> implementation, everything is been managed under HashMap<E,Object>.

作为HashMap的key.

而且我们知道 HashMap 不是线程安全的.这就是我们在 Java 中有 ConcurrentHashMap 的原因.

And we know that HashMap is not thread safe. That is why we have ConcurrentHashMap in Java.

基于此,我很困惑为什么我们没有应该基于 ConcurrentHashMap 的 ConcurrentHashSet?

Based on this, I am confused that why we don't have a ConcurrentHashSet which should be based on the ConcurrentHashMap?

还有什么我遗漏的吗?我需要在多线程环境中使用 Set.

Is there anything else that I am missing? I need to use Set in a multi-threaded environment.

另外,如果我想创建自己的 ConcurrentHashSet 是否可以通过将 HashMap 替换为 ConcurrentHashMap 并将其余部分保留为是吗?

Also, If I want to create my own ConcurrentHashSet can I achieve it by just replacing the HashMap to ConcurrentHashMap and leaving the rest as is?

推荐答案

ConcurrentHashSet 没有内置类型,因为您总是可以从地图中派生一个集合.由于有多种类型的地图,您可以使用一种方法从给定的地图(或地图类)生成一个集合.

There's no built in type for ConcurrentHashSet because you can always derive a set from a map. Since there are many types of maps, you use a method to produce a set from a given map (or map class).

在 Java 8 之前,您可以使用 Collections.newSetFromMap(map)

Prior to Java 8, you produce a concurrent hash set backed by a concurrent hash map, by using Collections.newSetFromMap(map)

在 Java 8 中(由@Matt 指出),您可以通过.这比旧的 newSetFromMap 简单一点,旧的 newSetFromMap 需要你传入一个空的地图对象.但它特定于 ConcurrentHashMap.

In Java 8 (pointed out by @Matt), you can get a concurrent hash set view via ConcurrentHashMap.newKeySet(). This is a bit simpler than the old newSetFromMap which required you to pass in an empty map object. But it is specific to ConcurrentHashMap.

无论如何,Java 设计者可以在每次创建新的地图界面时创建一个新的集合界面,但是当第三方创建他们自己的地图时,这种模式将无法实施.最好有派生新集合的静态方法;这种方法始终有效,即使您创建自己的地图实现也是如此.

Anyway, the Java designers could have created a new set interface every time a new map interface was created, but that pattern would be impossible to enforce when third parties create their own maps. It is better to have the static methods that derive new sets; that approach always works, even when you create your own map implementations.

这篇关于为什么没有针对 ConcurrentHashMap 的 ConcurrentHashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:24