0

In multiThreading I want to use a map which will be updated, which Map will be better considering the performance 1. HashMap 2. ConcurrentHashMap? also, will it perform slow if i make it volatile?

It is going to be used in a Java batch for approx. 20Million records. Currently i am not sharing this map among threads. will sharing the map among threads reduce performance?

3
  • You should provide a bit more context. What will it actually be used for? How many reads/writes per second are you expecting? This is information that enables the community to give you much higher quality answers. Keep this in mind for future questions you ask.
    – steliosbl
    Commented Jun 21, 2017 at 8:29
  • Thanks for your comment. it is going to be used for java batch as i edited in the question, i don'y have data for read/write per second. This batch can run using 80/100 threads Commented Jun 21, 2017 at 8:35
  • To add more detail(from AWR report) as asked by @Sty Physical reads(blocks) : 60.9 per sec Physical writes(blocks) : 1,358.1 per sec Commented Jun 21, 2017 at 8:59

1 Answer 1

1

HashMap will be better performance-wise, as it is not synchronized in any way. ConcurrentHashMap adds overhead to manage concurrent read and - especially - concurrent write access.

That being said, in a multithreaded environment, you are responsible for synchronizing access to HashMap as needed, which will cost performance, too.

Therefore, I would go for HashMap only if the use case allows for very specific optimization of the synchronization logic. Otherwise, ConcurrentHashMap will save you a lot of time working out the synchronization.

However, please note that even with ConcurrentHashMap you will need to carefully consider what level of synchronization you need. ConcurrentHashMap is thread-safe, but not fully synchronized. For instance, if you absolutely need to synchronize each read access with each write access, you will still need custom logic, since for a read operation ConcurrentHashMap will provide the state after the last successfully finished write operation. That is, there might still be an ongoing write operation which will not be seen by the read.

As for volatile, this only ensures that changes to that particular field will be synchronized between threads. Since you will likely not change the reference to the HashMap / ConcurrentHashMap, but work on the instance, the performance overhead will be negligible.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.