1

So I'm having this issue with my HashSet.

I am modyfing it from the Main-Thread and the FX8-Thread and now some Objects were added twice. Anyone know how to resolve this issue? Any help is highly appreciated!

MrMyth
  • 67
  • 6
  • 1
    Use a thread safe set. Use `putIfAbsent()`. – markspace Feb 08 '19 at 18:52
  • Weirdly, Java's concurrent set doesn't have a `putIfAbsent()` method. So perhaps use a `ConcurrentMap` and just store your elements as a both key and value the same object. https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/ConcurrentHashMap.html – markspace Feb 08 '19 at 18:58
  • Use `Set<...> mySet = Collections.newSetFromMap(new ConcurrentHashMap<..., ...>());` . See [this question](https://stackoverflow.com/questions/6992608/why-there-is-no-concurrenthashset-against-concurrenthashmap) for a discussion. – Bohemian Feb 08 '19 at 19:16

1 Answers1

1

HashSets are not thread safe. This somewhat older thread has a good discussion of thread safe sets: Different types of thread-safe Sets in Java

I'd start by making sure you're using a thread-safe Set implementation and then make sure your objects implement hashcode and equals methods according to what is described here https://www.geeksforgeeks.org/equals-hashcode-methods-java/

Taylor
  • 3,942
  • 2
  • 20
  • 33