Do I need a parallel hash map if each thread inserts unique keys?

From what I understand, a parallel hash map from Java 5 onwards gives you a hash map with a stream that does not use blocking access for iterators and updates (if the concurrency level is sufficient).

Given the following conditions:

  • Insertions are performed only once (during application initialization).
  • Each thread receives a set of keys for insertion that are not shared by any other thread.
  • Updates never happen.
  • Elections are made only after application initialization is complete.

Would I be better with simple hash maps?

I understand that I will probably be better, because my keys will not collide - I can guarantee this. But is it possible that the Java implementation will introduce errors in the hash buckets, for example, assigning the same bucket to two different keys?

+8
java hashmap concurrency
source share
2 answers

If you are inserting multiple streams, even if the keys are different, you should definitely use ConcurrentHashMap or synchronize the inserts. Normal HashMap simply unsafe for simultaneous recording. Suppose that two threads need to deploy an internal table at the same time ... although they use different keys, which is a fundamentally problematic situation.

Now, if you really have good evidence that using ConcurrentHashMap for the rest of your application life cycle is causing a problem (and I doubt very much that it is), you could create a parallel hash map to start with, convert it to a HashMap ( or even an immutable collection from Guava ) in one thread, making sure that there is a barrier between the "final map is published" and "the thread reads the final map".

+17
source share

If you have independent streaming keys, you can consider independent Maps. If this is an option, each thread can have its own HashMap, which should not be thread safe if it is used by only one thread.

+2
source share

All Articles