问题
We have Vector for List, and Hashtable for Map.
Similarly do we have any class which has thread safe methods for Set?
回答1:
One option: (java8)
Set<String> set = ConcurrentHashMap.newKeySet();
which is similar to HashSet, but also safe to use concurrently.
回答2:
There are ways to get thread safe sets. some e.g.
- CopyOnWriteArraySet
- Collections.synchronizedSet(Set set) etc
Check this for more details - Different types of thread-safe Sets in Java
回答3:
Vector
and Hashtable
are relics from before the Collection framework was introduced, and should be avoided if possible. The "new" way is to either use a specialized collection from the java.util.concurrent
package, or to make a normal List
/ Map
/ Set
and then use the Collections.synchronized...
utility to make them synchronized. See https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedSet-java.util.Set-
Remember to synchronize when using the iterator for objects obtained using Collections.synchronized...
as the iterators are not synched and manual synch is required. Without any synchronization can lead to ConcurrentModificationException
来源:https://stackoverflow.com/questions/31224559/is-there-any-threadsafe-class-for-set