ConcurrentHashMap: which point is only for blocking updates?

I always thought that ConcurrentHashMap and similar classes (which support synchronized updates and do not synchronize reading) did a very useful and intuitive thing: they did not block reading and blocked all functionality of updates. And such a strategy retains all coherence.

But I carefully read the documentation and opened the implementation of ConcurrentHashMap , and as I understand it, it does not block reading when another thread is doing updates. And if one thread starts to putAll(hugeCollection) and another thread repeats contains(theSameObjectForAllCalls) at the same time, then the second thread is more likely to get different results while putAll is still running.

Here is the part related to the documents:

For aggregate operations such as putAll and clear, parallel retrieval may reflect the insertion or deletion of only certain entries.

Another interesting thing:

Retrievals reflect the results of the most recently completed operation update performed after they started.

This does not work because of some blockage, but because a new object is added first, and only after the object counter is incremented and the object becomes visible for read operations.

So what is the purpose of updating updates?

+7
java performance multithreading concurrency locking
source share
2 answers

Brian Goetz explained working in an article while working with developers. This should help.

+4
source share

These classes give you extra control over the tradeoffs around concurrency compared to consistency. If what you really want is atomic consistent reading, then get a synchronized hash file. However, if you need more concurrency, you can get a ConcurrentHashMap if you know that the readings will get an accurate picture of what the map looked like at some point, just not necessary now.

The trade-off is that you need to think more about data consistency, but your application may have much more concurrency.

+4
source share

All Articles