Difference Between ConcurrentHashMap and SynchronizedHashMap
The ConcurrentHashMap and SynchronizedHashMap both are the Collection classes which are thread-safe and can be used in multithreaded and concurrent java application. But there are few differences that exists between them. In this article, we have tried to cover all these differences between them.
1. ConcurrentHashMap: ConcurrentHashMap is a class which implements the ConcurrentMap interface. It uses Hashtable, underlined data structure. As we know, while dealing with thread in our application HashMap is not a good choice because of the performance issue. To resolve this issue, we use ConcurrentHashMap in our application. ConcurrentHashMap is thread-safe therefore multiple threads can operate on a single object without any problem. In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level. By default, it allows 16 thread to read and write from the Map without any synchronization. In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updating in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence, at a time16 update operations can be performed by threads.
Key = 50, Value = you Key = 20, Value = for Key = 40, Value = Welcome Key = 10, Value = Geeks Key = 30, Value = Geeks
2. Synchronized HashMap: Java HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly. The synchronizedMap() method of java.util.Collections class is used to synchronize it. It returns a synchronized (thread-safe) map backed by the specified map.
Synchronized HashMap Demo:
20: for 40: you 25: Welcome 10: Geeks 30: Geeks
Difference between ConcurrentHashMap and Synchronized HashMap: ConcurrentHashMap Synchronized HashMap
ConcurrentHashMap is a class that implements the ConcurrentMap and serializable interface. We can synchronize the HashMap by using the synchronizedMap() method of java.util.Collections class. It locks some portion of the map. It locks the whole map. 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. ConcuurentHashMap doesn’t allow inserting null as a key or value. Synchronized HashMap allows inserting null as a key. ConccurentHashMap doesn’t throw ConcurrentModificationException. Synchronized HashMap throw ConcurrentModificationException.