[Solved] Is Java HashSet add method thread-safe?


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.

solved Is Java HashSet add method thread-safe?