Do I need a ConcurrentHashMap in Java for this case:
Before, passing the HashMap to a bunch of threads, I initiate the map with all the keys necessary:
Key = "thread1Key", Value = null
Key = "thread2Key", Value = null
Key = "thread3Key", Value = null
...
Each task is part of a Runnable (executed by a thread) and is assigned to alter the value of ONLY 1 of those keys. It's preassigned. In other words, I don't need to worry about the case where multiple Runnables may alter the same key in the hashmap.
In this case is ConcurrentHashMap required or a regular HashMap would do? And why?
Thanks!
This usage of HashMap
is safe without additional synchronization. The docs describe exactly your use case:
If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)