Original link: https://zhuanlan.zhihu.com/p/613889543
Map<String, Object> map1 = new HashMap<String, Object>();
Map<String, Object> map2 = new Hashtable<String, Object>();
Map<String, Object> map3 = new ConcurrentHashMap<String, Object>();
Map<String, Object> map4 = Collections.synchronizedMap(new HashMap<String, Object>());
Thread safety is different
Collections.synchronizedMap uses the synchronized keyword in each method for synchronization.
ConcurrentHashMap uses segment locks (Segment) to achieve thread safety and divides a large Map into multiple small Segments. Each Segment has its own With the lock, different threads can access different Segments at the same time, thereby improving concurrency performance.
Different thread safety levels
Collections.synchronizedMap can only guarantee the atomicity of a single operation on the Map, but cannot guarantee the atomicity of multiple operations. Therefore, in a multi-threaded environment, the user needs to ensure the atomicity of the operation.
For example: between map reading and clearing, threads are not synchronized. The correct way is to regard the reading and clearing of the map as an atomic operation and lock the entire code block.
ConcurrentHashMap can guarantee atomicity for multiple operations.
Iterators are different
The iterators in Collections.synchronizedMap are synchronized, that is, other threads cannot modify the contents of the Map during the iteration. The
iterators in ConcurrentHashMap are weakly consistent, that is, other threads can modify the contents of the Map during the iteration, but not Ensure that the iterator can access the latest modifications.
Null values are different
ConcurrentHashMap does not allow to store null,
Collections.synchronizedMap can store null.
Different memory usage
ConcurrentHashMap uses segmented locks to achieve thread safety, so its memory usage is higher than Collections.synchronizedMap.
Different expansion methods
The expansion method of ConcurrentHashMap is achieved by increasing the number of Segments, while the expansion method of Collections.synchronizedMap is achieved by creating a new Map and copying the contents of the old Map to the new Map.
The underlying implementation is different
Collections.synchronizedMap is implemented using a wrapper class.
ConcurrentHashMap is implemented using arrays and linked lists
Summary:
ConcurrentHashMap performs better under high concurrency
. Collections.synchronizedMap is simpler and easier to use under low concurrency.
Therefore, the appropriate thread-safe Map implementation class should be selected based on the actual situation.
Further Reading
What scenarios are synchronizedMap and concurrenthashmap suitable for?
The difference between Collections.synchronizedMap() and ConcurrentHashMap