【问题标题】:How to do ConcurrentHashMap.computeIfAbsent without assigning the entry to hashmap?如何在不将条目分配给 hashmap 的情况下执行 ConcurrentHashMap.computeIfAbsent?
【发布时间】:2019-10-25 13:57:11
【问题描述】:

有没有办法模拟 ConcurrentHashmap.computeIfAbsent 但不将条目分配给哈希图。我只需要当哈希图中的条目不存在时该方法生成的实例。这些在线程中运行。所以我需要它是线程安全的。

我已经尝试过同步块,但这将保存整个哈希。我希望它像 computeIfAbsent。

synchronized(hashMap) {
    if (hashMap.contains(key)) {
        rs = hashMap.get(key);
    } else {
        rs = createNewInstance();
    }
}


/* this would be perfect, but I don't what the new instance to be in the hashMap */
rs = hashMap.computeIfAbsent(key, k -> createNewInstance());

【问题讨论】:

  • 规范 computeIfAbsent()If the function returns null no mapping is recorded. 也许你可以实现方法 createNewInstance() 返回 null,然后 sn-p rs = hashMap.computeIfAbsent(key, k -> createNewInstance()); 将按预期工作:-)。

标签: java


【解决方案1】:

我猜你可以这样做:

AtomicReference<Foo> holder = new AtomicReference<>();
map.computeIfAbsent(key, k -> {
  holder.set(/* compute the value */);
  return null;  // returning null means no value is stored.
});
/* Use holder.get() to access value */

但这是一个非常不寻常的要求。

【讨论】:

    【解决方案2】:

    您可以改用map.getOrDefault(key, defaultValue)

    【讨论】:

    • 这个问题是即使不需要它也会创建实例。有没有类似 map.getOrComputeIfAbsent 的东西?
    • 不,getOrDefault 没有供应商版本。你的用例是什么,为什么不把它放在地图上?
    • @user3682563 找到了一个关于它的older questionOptional 方法可行吗?
    • 我不确定 Optional 是否是线程安全的。很可能不是。恐怕很多相同key的线程都会触发createNewInstance。
    • @user3682563 但这就是你想要的。您不希望值进入映射,因此对于相同的键 10 次调用将生成 10 个新实例,无论是否涉及线程。至于 Optional,这里是线程安全的,因为它是一个局部变量。同一个Optional 永远不能涉及多个线程。
    【解决方案3】:

    没有这样的方法。如果值不存在,您可以使用 get 返回 null 的事实:

    public static void main(String[] args) {
        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
        Object rs = Optional.ofNullable(map.get("key"))
                .orElseGet(() -> "created instance");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多