Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concurrent HashMap: checking size

Concurrent Hashmap could solve synchronization issue which is seen in hashmap. So adding and removing would be fast if we are using synchronize key work with hashmap. What about checking hashmap size, if mulitple threads checking concurrentHashMap size? do we still need synchronzation key word: something as follows:

public static synchronized getSize(){
     return aConcurrentHashmap.size();
}  
like image 351
user84592 Avatar asked Apr 25 '12 10:04

user84592


People also ask

How to check the size of a ConcurrentHashMap?

So to answer you question here, checking size of ConcurrentHashMap doesn't help because, it keeps chaining based on the operations or modification code that you write on the map. It has size method which is same from the HashMap.

Does ConcurrentHashMap throw a ConcurrentModificationException?

ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it. ConcurrentHashMap does not allow NULL values, so the key can not be null in ConcurrentHashMap

What is concureenthashmap in Java?

ConcurrentHashMap ConcurrentHashMap class is introduced in JDK 1.5, which implements ConcurrentMap as well as Serializable interface also. ConcureentHashMap is enhancement of HashMap as we know that while dealing with Threads in our application HashMap is not a good choice because performance wise HashMap is not upto the mark.

Are concurrent HashMap and hashtable thread safe?

Even though both Concurrent HashMap and Hashtable are thread safe. But Hash Table have a poor performance in the Multi Threading usage. If one thread allows to perform any kind of operation (put or get) , other thread must and should wait until the operation was completed by the thread which is working on hash Table.


1 Answers

concurentHashMap.size() will return the size known at the moment of the call, but it might be a stale value when you use that number because another thread has added / removed items in the meantime.

However the whole purpose of ConcurrentMaps is that you don't need to synchronize it as it is a thread safe collection.

like image 161
assylias Avatar answered Oct 14 '22 22:10

assylias