Is there any threadsafe class for Set

我们两清 提交于 2020-12-16 05:32:04

问题


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.

  1. CopyOnWriteArraySet
  2. 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

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