带有 Guava 集合的线程安全 HashSet

发布于 2024-09-16 22:28:15 字数 66 浏览 1 评论 0原文

就像标题所说,我想使用 Guava Collections 获得一个线程安全的 HashSet。
有可用的吗?

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

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

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

发布评论

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

评论(4

醉生梦死 2024-09-23 22:28:15
Set<K> set = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>());
Set<K> set = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>());
半步萧音过轻尘 2024-09-23 22:28:15

这将是正确的答案,使用 Guava 的 Sets 类。不管怎样,@crhis 的回答是好的。

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

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

Sets.newSetFromMap(new ConcurrentHashMap<V, Boolean>());
待"谢繁草 2024-09-23 22:28:15

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

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

它比包装在 Collections.newSetFromMap 中要短

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

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

It's shorter than wrapping in Collections.newSetFromMap

冷了相思 2024-09-23 22:28:15

Google Collections一个名为Sets.newConcurrentHashSet() 一段时间。

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

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

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

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

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

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

Its implementation was similar to Chris's suggestion:

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

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

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

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

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