Suppose we have multiple threads and we're dividing the possible keySet between the threads (i.e. key % thread_i
) so there's no key collision.
Can we safely use HashMap<T>
instead of ConcurrentHashMap<T>
?
Suppose we have multiple threads and we're dividing the possible keySet between the threads (i.e. key % thread_i
) so there's no key collision.
Can we safely use HashMap<T>
instead of ConcurrentHashMap<T>
?
No, for several reasons. Some (but not all) would be:
If you constructed your map with a particular jvm implementation in mind, and made sure that your map never resized, and knew you'd never care about that extra state, it's maybe possible, in the strictest of senses. But for any practical purposes, no.
The Javadoc is very clear about how you should use HashMap
in multithreaded applications (I didn't even add the emphasis on "must" myself):
If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
It's not beating about the bush here. You can use it safely provided you synchronize appropriately (which basically means to ensure mutually exclusive access to the map across threads).
If you do anything other than what it directly tells you, you are on your own.
Maybe it will work, if you pre-populate the map with dummy values for each keys, before starting the different threads. But:
A better option is to use a local map for each thread and join the local map at the end to collect the results.