【问题标题】:Best practice to update ConcurrentHashMap with atomic values使用原子值更新 ConcurrentHashMap 的最佳实践
【发布时间】:2022-02-03 09:20:26
【问题描述】:

我有ConcurrentHashMap<String, AtomicReference<String>> 地图,我需要更新其中的一些值。 我写了以下代码:

map.compute(key) { _, value ->
   value?.also { reference -> 
      reference.set(getNewValue())
   }
}

它运作良好,但我不确定它是否是这种情况下的最佳解决方案。有没有更好的做法?

【问题讨论】:

  • compute 确实已经在锁定下执行了计算,因此使用额外的AtomicReference<String> 没有意义。您可以简单地使用ConcurrentHashMap<String, String>

标签: kotlin collections concurrency concurrenthashmap


【解决方案1】:

您当前的代码不清楚您的意图:

map.compute(key) { _, value ->
   value?.also { reference -> 
      reference.set(getNewValue())
   }
}

我不确定这是否确实是您的意图,但是根据您所写的,如果键不存在,它将不会插入新值。 lambda 将收到 null 对应的 value,而您的 lambda 定义将返回相同的 null

为了更清楚地表达你的意图,让它更明显:

map[key]?.also { reference -> 
  reference.set(getNewValue())
}

但正如 Holger 在对您的问题的评论中所说,使用 AtomicReference 毫无意义。请改用ConcurrentMap<String, String>

map.computeIfPresent(key) { getNewValue() }

但是:

如果您的意图实际上是更新现有的插入新值

那么就这样做吧:

map[key] = getNewValue()

如果出于某种奇怪的原因,您真的必须使用AtomicReference,那么请执行以下操作:

map.getOrPut(key, AtomicReference<String>()).set(getNewValue())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2022-08-02
    • 2010-10-01
    相关资源
    最近更新 更多