You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ConcurrentHashMap::get方法是否返回脏值?put写入时读同key得何值?

ConcurrentHashMap::get: Will it return "dirty values"?

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 Node class holding key-value pairs in ConcurrentHashMap has its val field marked as volatile. This ensures any write to val is atomic and, once completed, immediately visible to other threads.
  • When updating an existing value via put(), the operation uses atomic mechanisms (like UNSAFE.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 new Node before linking it into the bucket structure. The link operation uses CAS (Compare-And-Swap), which guarantees the node is either fully added or not—so get() 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 (or null if the key didn’t exist before).
  • Once the put() completes its atomic write/linking, all subsequent get() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:57:04