1.

What is ConcurrentHashMap and Hashtable? In java, why is ConcurrentHashMap considered faster than Hashtable?

Answer»

ConcurrentHashMap: It was introduced in Java 1.5 to store data using multiple buckets. As the name SUGGESTS, it allows CONCURRENT READ and writes operations to the map. It only locks a certain portion of the map while doing iteration to provide thread safety so that other readers can still have access to the map WITHOUT waiting for iteration to complete.  

Hashtable: It is a thread-safe legacy class that was introduced in old versions of java to store key or value pairs using a hash table.  It does not provide any lock-free read, unlike ConcurrentHashMap. It just locks the entire map while doing iteration. 

ConcurrentHashMap and Hashtable, both are thread-safe but ConcurrentHashMap generally avoids read locks and improves performance, unlike Hashtable. ConcurrentHashMap also provides lock-free reads, unlike Hashtable. THEREFORE, ConcurrentHashMap is considered faster than Hashtable especially when the number of readers is more as compared to the number of writers. 



Discussion

No Comment Found