Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which map implementation to use if multiple threads write to a single map

In my application I would be using a Map.

  • Multiple threads would be writing data to this map. The write operations are too many.
  • However, the data that is fed to the map has a different key during every write.
  • The data in the map would not be read at any point in the application.
  • Once in a while, the content would be dumped to a file.

I would like to know the following :

  1. In this case, would it be necessary to synchronize the write method?
  2. Does a ConcurrentHashMap suit my needs?
  3. If not, what would be the right Map implementation to use in this case?
like image 352
sujith Avatar asked Sep 12 '26 15:09

sujith


1 Answers

Focusing on these points:

  • The data that is fed to the map has a different key during every write

  • The data in the map would not be read at any point in the application

You don't need a Map at all. I'm assuming that when you state that the data in the map won't be read, you mean that you're not doing map.get(someKey) but instead you will traverse the whole map to store the data in the file (or whatever data source you use).

This point:

  • Once in a while the content would be dumped to a file

Reinforces the recommendation above.

Focusing on this point:

  • Multiple threads would be writing data to this map.The write operations are too many.

The best recommendation is to use a BlockingQueue. As implementation, you may use LinkedBlockingQueue.

In case you dump the data from the Map using Java synchronization and want/need to recover this data in form of a Map, then use a ConcurrentHashMap. If this is not part of your use case because you will read the data from the file on other ways, then avoid using Map and use BlockingQueue.

like image 185
Luiggi Mendoza Avatar answered Sep 15 '26 05:09

Luiggi Mendoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!