简体   繁体   中英

Java concurrent hashMap retrieval

ConcurrentHashMap documentation says:

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. (More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.)

But I am not able to understand how retrieval operation do not block with update/remove operation for same key ?

"an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key"

that sort of indicate that concurrent hash map has some way create sequence for read/update/remove operations on same key. But that mean read operations are blocked by update/remove operations.

Not sure what I am missing here.

But I am not able to understand how retrieval operation do not block with update/remove operation for same key ?

First of all, "how" it does it is an implementation detail. If you really want / need to understand "how", you need to look at the source code. It is available from various places.

But what this is actually saying is that:

  • get doesn't block, and
  • what you see when you do a get is the value from the most recently completed put operation for that key.

So if you do a get while a put is in progress, you may see the value from the previous put .

Note that the 2nd bullet point explains (implicitly) why it is possible for get to be non-blocking. There is no need for get(42) to wait for a put(42, value) that is currently in progress to finish ... since the get call is allowed to return the previous value.

TL;DR - there is no need to block.


The stuff about " happens before " relationships is relating this to the semantics of the Java Memory Model. This may be important if you are doing a deep analysis of your code. But for a shallow understanding of what ConcurrentHashMap does, you can ignore it.

... that sort of indicate that concurrent hash map has some way create sequence for read/update/remove operations on same key.

It doesn't imply that at all. But to understand what the statement you quoted really means, you need a need a good understanding of the Java Memory Model. And I don't think it is feasible to convey that to you in a StackOverflow Q&A. I recommend you take a few hours to read and understand the JMM ... by reading the JLS. Then, do it again.

This is NOT stuff where an intuitive understanding is sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM