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

问题描述

HashSet基于HashMap。



如果我们看一下 HashSet< E> HashMap< E,Object> 下管理。



< E> c $ c>用作 HashMap 的键。



我们知道 HashMap 不是线程安全的。这就是为什么我们在Java中有 ConcurrentHashMap



基于这个,我很困惑,没有ConcurrentHashSet,应该基于 ConcurrentHashMap



我失踪了?我需要在多线程环境中使用 Set



此外,如果我想创建自己的 ConcurrentHashSet 可以通过替换 HashMap ConcurrentHashMap

ConcurrentHashSet 没有内置类型 c>,因为您可以随时从地图中导出集合。因为有很多类型的地图,所以你使用一个方法从给定的地图(或地图类)中产生一个集合。



在Java 8之前,哈希集,并使用



在Java 8(@Matt ),您可以通过。这比旧的 newSetFromMap 简单一些,它要求你传递一个空的地图对象。但是它特定于 ConcurrentHashMap



无论如何,Java设计者可能每次创建一个新的设置接口创建了新的地图界面,但是当第三方创建自己的地图时,该模式将无法实施。最好有静态方法派生新集合;即使你创建自己的地图实现,这种方法总是奏效。


HashSet is based on HashMap.

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

<E> is used as a key of HashMap.

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

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

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

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?

解决方案

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

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

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.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:19