Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap or ConcurrentHashMap for single writer / single reader scenario?

Here are the details.

  1. One thread writes to the map, another thread reads from it.
  2. A key once inserted is never updated.
  3. If consumer thread doesn't find the value in the map, it can compute the value itself. It won't find 1% of the values, as they would not have been computed by the producer thread.
  4. When the consumer asks for a value, it should get it as fast as possible.

Will HashMap without synchronization work in this case? Or I will have to use ConcurrentHashMap?

like image 488
q126y Avatar asked Sep 13 '25 07:09

q126y


2 Answers

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.

like image 61
BarrySW19 Avatar answered Sep 14 '25 21:09

BarrySW19


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.

like image 21
Sergey Kalinichenko Avatar answered Sep 14 '25 23:09

Sergey Kalinichenko