-4

The Java HashSet add method combines a contains and an add method as it returns true or false if the element is already present in the collection.

Is the add method atomic? I can use it in a multi-thread configuration and it will ensure that both operations will be run sequentially or the add method can be suspended between checking whether the element is present and effectively adding it to the collection?

leokury
  • 429
  • 1
  • 4
  • 15
  • 3
    much probably not, see the first pages of the same [link](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/HashSet.html) you provided: "**Note that this implementation is not synchronized.** If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally." (emphasis NOT mine) – user16320675 Sep 04 '22 at 12:18
  • https://stackoverflow.com/questions/6992608/why-there-is-no-concurrenthashset-against-concurrenthashmap The above thread might be an interesting read for you. Within such a thread, some recommendations AND discussions can be found. I would lean away from saying HashSet is thread safe, like the previous commenter suggested... the docs claim otherwise. How strict a requirement is it to use HashSet? – Java-Enthusiast Sep 04 '22 at 12:27
  • Use ConcurrentHashMap and use Boolean.TRUE for the value of every key. – access violation Sep 04 '22 at 12:31
  • Neater as `Set set = ConcurrentHashMap.newKeySet();` – DuncG Sep 04 '22 at 14:52
  • The question is specific about the add method. Is this method atomic or it can be suspended during the execution? – leokury Sep 05 '22 at 11:20

1 Answers1

1

No, HashSet is not thread-safe.

You can use your own synchronization around it to use it in a thread-safe way:

boolean wasAdded;
synchronized(hset) {
    wasAdded = hset.add(thingToAdd);
}

If you really need lock-free performance, then you can use the keys of a ConcurrentHashMap as a set:

boolean wasAdded = chmap.putIfAbsent(thingToAdd,whatever) == null;

Keep in mind, though, that ConcurrentHashMap takes a lot of memory and it isn't super fast.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87