Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe HashSet with Guava Collections

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

like image 969
santiagobasulto Avatar asked Sep 02 '10 16:09

santiagobasulto


People also ask

Are HashSet thread-safe?

2. Non-Thread-Safe Set Implementations. We'll first look at the non-thread-safe Set implementations including HashSet, LinkedHashSet, and TreeSet. When accessed from multiple threads concurrently, these Set implementations may not behave correctly.

Is ConcurrentHashMap newKeySet thread-safe?

Thread Safe HashSet Using ConcurrentHashMap Factory Method Firstly we'll look at the ConcurrentHashMap class that exposed the static newKeySet() method. Basically, this method returns an instance that respects the java. util. Set interface and allows the usage of standard methods like add(), contains(), etc.

Is C# HashSet thread-safe?

Collections and related namespaces can be read by multiple threads safely. This means HashSet can be safely read by multiple threads.

Why there is no concurrent HashSet in Java?

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). Set s = Collections. synchronizedSet(new HashSet(...));


2 Answers

Set<K> set = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>());
like image 52
Chris Jester-Young Avatar answered Sep 22 '22 22:09

Chris Jester-Young


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>());
like image 31
santiagobasulto Avatar answered Sep 24 '22 22:09

santiagobasulto