Like the title says, i would like to get a thread-safe HashSet using Guava Collections.
Are any available?
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.
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.
Collections and related namespaces can be read by multiple threads safely. This means HashSet can be safely read by multiple threads.
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(...));
Set<K> set = Collections.newSetFromMap(new ConcurrentHashMap<K, 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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With