Here are the details.
Will HashMap
without synchronization work in this case? Or I will have to use ConcurrentHashMap
?
The short answer is that you need a ConcurrentHashMap
.
The slightly longer explanation is that there are two reasons for this. Firstly, a simple HashMap
risks reader and writer threads working on the same internal data of the HashMap
at the same time. For a HashMap
to maintain its correctness it obviously has to update multiple internal properties in a way that has to appear to happen as a single operation to any client. Allowing a reader to query the HashMap
while a writer is busy modifying these properties can lead to unexpected behaviour.
The second point is that the visibility of changes made by one thread are not available in a predictable manner to other threads without the use of Java's concurrent support mechanisms. So, even if a writer finished before a reader queries the HashMap
there is no guarantee the reader would see the data as the writer left it - a ConcurrentHashMap
takes care of this problem.
The first point is something which is more likely on single processor machines where a writer thread may complete part of its work of inserting a new value and then yield while a reader thread reads from the partially updated map. The second point is more of an issue on multi-core machines where each core will have its own version of shared memory which only gets synchronised with other cores predictably if you use concurrency mechanisms.
If you plan to read and write from a map from multiple threads concurrently, you need ConcurrentHashMap
. HashMap
will not do, because an attempt to execute a get
concurrently with a put
may lead to incorrect behavior.
If the writing thread finishes before the reading thread starts, you could use regular HashMap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With