Monday, February 19, 2018

How CuncurrentHashMap Works Internally

Hashtable locks entirely to perform any sort of operation. While this overhead is ignorable in a web application under normal load, under heavy load it can lead to delayed response times and overtaxing of your server for no good reason.

This is where ConcurrentHashMap introduced. It offers all the features of Hashtable with a performance almost as good as a HashTable. ConcurrentHashMap accomplish this by a very simple mechanism. Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to lock on a single bucket of the map. This effectively means that 16 threads can modify the collection at a time as long as they’re all working on different buckets.Infact there is no operation performed by this collection that locks the entire map. The concurrency level of the collection, the number of threads that can modify it at the same time without blocking, can be increased. However a higher number means more overhead of maintaining this list of locks

The ConcurrentHashMap is very similar to the java.util.HashTable class, but the ConcurrentHashMap offers better concurrency than HashTable / synchronizedMap does. ConcurrentHashMap does not lock the entire Map while you are reading from it. Additionally,ConcurrentHashMap does not lock the entire Map when writing to it. It only locks the part of the Map that is being written to, internally.

Another difference is that ConcurrentHashMap does not throw ConcurrentModificationException if the ConcurrentHashMap is changed while being iterated. In the case of synchronizedMap the Iterator is not designed to be used by more than one thread if so it may throw ConcurrentModificationException

Overall Functioning of CuncurrentHashMap

-->Multiple partitions which can be locked independently. (16 by default)
-->Using concurrent Locks operations for thread safety instead of synchronized.
-->Has thread safe Iterators. synchronizedCollection's iterators are not thread safe.
-->Does not expose the internal locks. synchronizedCollection does.


Thanks for reading. If you like this post please follow us for more updates about technology related updates.

No comments: