Are get(Key)
method calls for a a standard HashMap
and a ConcurrentHashMap
equal in performance when no modifications happen for the underlaying Map (so only get() operations are performed.)
Update with Background:
Concurrency is quite a komplex topic: I do nead "concurrency/threadsafety" but only on puts, that happen extremely seldom. And for the puts I could swap the Map Associations itself (which is atomic and threadsafe). Therefore I am asking I am doing a lot of gets (and have the option to either implement it with a HashMap (create a temporary Hashmap, Copy Data into new HashMap, and swap association) or using a ConcurrentHashMap... As my App really doeas a lot of gets I want to learn more how performance is lost with both different gets. As silly this sounds, the internet has so much unnecessary information around but this is something I think could be of interest to a lot more people. So if someone knows the inner workings of ConcurrentHashMap for gets it would be great to answer the question.
Thanks very much!
If you choose a single thread access use HashMap , it is simply faster. For add method it is even as much as 3x more efficient. Only get is faster on ConcurrentHashMap , but not much. When operating on ConcurrentHashMap with many threads it is similarly effective to operating on separate HashMaps for each thread.
Hashtable is belongs to the Collection framework; ConcurrentHashMap belongs to the Executor framework. Hashtable uses single lock for whole data. ConcurrentHashMap uses multiple locks on segment level (16 by default) instead of object level i.e. whole Map . ConcurrentHashMap locking is applied only for updates.
ConcurrentHashMap allows performing concurrent read and write operation. Hence, performance is relatively better than the Synchronized Map. In Synchronized HashMap, multiple threads can not access the map concurrently. Hence, the performance is relatively less than the ConcurrentHashMap.
The default concurrency-level of ConcurrentHashMap is 16. In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate.
According to the ConcurrentHashMap
API, there is no locking for retrieval methods. So, I'd say they are equal in performance.
You're asking the wrong question.
If you need concurrency, you need it no matter the performance impact.
A correctly behaving program almost always ranks more highly than a faster program. I say "almost always" because there may be business reasons to release software with bugs rather than holding back until the bugs are fixed.
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