ConcurrentHashMap::get方法是否返回脏值?put写入时读同key得何值?
Great question—this is a common point of confusion when working with concurrent collections in Java! Let's break this down clearly:
First: No "garbage values" will ever be returned
You can rest easy here—a get() call will never return a partial, corrupted, or "garbage" value when another thread is performing a put(). Here's why:
- In Java 8+, the
Nodeclass holding key-value pairs inConcurrentHashMaphas itsvalfield marked asvolatile. This ensures any write tovalis atomic and, once completed, immediately visible to other threads. - When updating an existing value via
put(), the operation uses atomic mechanisms (likeUNSAFE.putObjectVolatile) to swap the old value with the new one. There’s no intermediate state where only part of the value is written—either the full old value is present, or the full new one is. - For inserting new entries,
put()fully constructs the newNodebefore linking it into the bucket structure. The link operation uses CAS (Compare-And-Swap), which guarantees the node is either fully added or not—soget()will never see a partially linked entry.
What you will get: Either the old value or the new value
When a put() is in progress while another thread calls get(), the result depends on timing:
- If the
put()hasn’t finished writing the new value (or linking the new node),get()will return the old value (ornullif the key didn’t exist before). - Once the
put()completes its atomic write/linking, all subsequentget()calls will return the new value.
It’s worth noting that ConcurrentHashMap provides weak consistency for reads. This means a get() might briefly return the old value even after the put() finishes, if the reading thread hasn’t yet picked up the updated value from main memory (due to CPU caching). But this is temporary—volatile’s visibility guarantees ensure the reading thread will eventually see the new value. This is a deliberate trade-off for the performance benefits of non-blocking reads.
To sum up
- No garbage or corrupted values—ever.
- Reads during an ongoing
put()will return either the full old value or the full new value. - Weak consistency means you might see stale values briefly, but never invalid ones.
内容的提问来源于stack exchange,提问作者Vaithilingam K

