java 带有 Guava 集合的线程安全 HashSet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3629359/
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 02:43:51  来源:igfitidea点击:

Thread-safe HashSet with Guava Collections

javacollectionshashsetguava

提问by santiagobasulto

Like the title says, i would like to get a thread-safe HashSet using Guava Collections.
Are any available?

正如标题所说,我想使用 Guava Collections 获得线程安全的 HashSet。
有没有可用的?

采纳答案by santiagobasulto

This would be the right answer, Using the Sets class from Guava. Anyway the answer from @crhis was good intended.

这将是正确的答案,使用 Guava 的 Sets 类。无论如何,@crhis 的回答是好的。

Sets.newSetFromMap(new ConcurrentHashMap<V, Boolean>());

回答by Chris Jester-Young

Set<K> set = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>());

回答by turbanoff

Java 8 introduces new way to create concurrent hash set - ConcurrentHashMap.newKeySet()

Java 8 引入了创建并发散列集的新方法 - ConcurrentHashMap.newKeySet()

Set<K> set = ConcurrentHashMap.newKeySet();

It's shorter than wrapping in Collections.newSetFromMap

它比包装短 Collections.newSetFromMap

回答by Etienne Neveu

Google Collections hada factory method named Sets.newConcurrentHashSet()for a while.

Google Collections一个名为Sets.newConcurrentHashSet()的工厂方法有一段时间了。

Its implementation was similar to Chris's suggestion:

它的实现类似于 Chris 的建议:

public static <E> Set<E> newConcurrentHashSet() {
  return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}

They had a newSetFromMap()method inside the com.google.common.collect.Setsclass (written by Doug Lea with assistance from members of JCP JSR-166). That method was added to java.util.Collectionsin java 1.6.

他们在com.google.common.collect.Sets类(由 Doug Lea 在 JCP JSR-166 成员的帮助下编写)中有一个newSetFromMap()方法。该方法在 java 1.6 中被添加到java.util.Collections中。

It was withdrawn in Google Collections 1.0rc1, since there are plans to better support concurrent sets in Guava (more information here).

它在 Google Collections 1.0rc1 中被撤回,因为有计划更好地支持 Guava 中的并发集(更多信息在这里)。

This postexpands on the use of the "newSetFromMap" method to construct concurrent sets.

这篇文章扩展了使用“newSetFromMap”方法来构造并发集。