Why is synchronizedMap () needed when there is a ConcurrentHashMap?
I read an article about streaming protected maps and got a question. Collections.synchronizedMap()
proxies the basemap, adding blocks synchronized
for each method. On the other hand, it ConcurrentHashMap
does not block the entire card read / write operations. This means that all operations on a multithreaded system are faster.
What are the benefits of using it synchronizedMap()
now? I see the only thing:
- it is available since java 1.2 (vs java 1.5 for
ConcurrentHashMap
) - can store null-valued values โโ(if the basemap can do that)
Are there other situations where synchronizedMap()
it is better?
source to share
There are pros and cons associated with Collections.synchronizedMap(map)
both ConcurrentHashMap
.
synchronizedMap
useful if you need data consistency. Each access thread will have a map refresh view, which is achieved by blocking the map, which in turn degrades its performance.
ConcurrentHashMap
useful when you need to change frequently map
. Since it works with segmentation / splitting map
, multiple threads are running on it at the same time. But there is a possibility that the access flow may not be in the form of a map update. Another advantage is that it is fail-safe
. does not allow null keys or values. ConcurrentHashMap
Use ConcurrentHashMap
if performance is more important than data consistency.
source to share
From the ConcurrentHashMap documentation:
"... there is no support for locking an entire table in a way that prevents all access"
As you iterate through the elements of the ConcurrentHashMap, you can see the updates performed at the same time by other threads. If you want to prevent such updates, you can use Collections.synchronizedMap () instead and put your iteration logic in a synchronization (map) block.
source to share
I can translate this with the Mutex and Semaphore anology.
Like any Mutex, synchronizedMap only allows one thread to access the support map. This ensures that no other thread can read / write writes from the card.
And for ConcurrentHashMap, as well as for Semaphores, we decide the concurrency level, that is, how many threads at one time can actually enter and look into your Map.
Researching when to use Mutex and when to use Semaphore can help you further clarify your doubts.
source to share