Thread-safe HashSet with Guava Collections

无人久伴 提交于 2019-12-12 08:20:11

问题


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

Can you help me?

Thanks!


回答1:


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



回答2:


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>());



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/3629359/thread-safe-hashset-with-guava-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!