1

We have Vector for List, and Hashtable for Map.

Similarly do we have any class which has thread safe methods for Set?

Onki
  • 1,879
  • 6
  • 38
  • 58

3 Answers3

6

One option: (java8)

Set<String> set = ConcurrentHashMap.newKeySet();

which is similar to HashSet, but also safe to use concurrently.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61
  • almost the same as `Collections.newSetFromMap(new ConcurrentHashMap<>())`: see https://stackoverflow.com/questions/32054517/concurrenthashmap-newkeyset-vs-collections-newsetfrommap – Ilya Serbis Apr 28 '21 at 20:20
3

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

Community
  • 1
  • 1
Raman Shrivastava
  • 2,923
  • 15
  • 26
1

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

wggn
  • 77
  • 6
  • Collections.synchronized... are less efficient than specialized concurrent data structures since they are simply wrappers that synchronize on *every* call. It is better to use `java.util.concurrent.ConcurrentFoo` when possible. – nanofarad Jul 04 '15 at 19:56