I have a multithreading app. Multiple threads are putting things into a Map in which each thing must have a unique ID. Right now I'm using a TreeMap for this purpose like this:
TreeMap<Integer, Thing> things = new TreeMap<>();
things.put(things.isEmpty() ? 0 : things.lastKey() + 1, thing);
But a TreeMap is not thread-safe, so I decided to replace it with a ConcurrentHashMap.
But how could I achieve the same using a HashMap? So how to generate a new unique key for each thing I put into it?
You can generate unique Integers using Javas AtomicInteger class. It has a thread-safe getAndIncrement() method for that purpose.
However, this may cause some unpredictable bug in HashMap even with different keys. Some example listed here: Is a HashMap thread-safe for different keys?
So be sure to use a thread-safe map, or some other faster thread-safe datastructure like a Vector. If you know an upper bound of how many elements will be added, using an array with the index from AtomicInteger would be fastest, as you can avoid all synchronization.