gpt4 book ai didi

java - 映射允许 putIfAbsent 键已经存在时不创建值

转载 作者:行者123 更新时间:2023-11-30 06:30:49 28 4
gpt4 key购买 nike

我想使用一个等同于 ConcurrentMap 的 map (我想要等同于 putIfAbsent 方法)但这不会强制我创建事先反对。

例如当我这样做时:

m.putIfAbsent( key, new CyclingArray() );

我最终可能会白白创建一个新的CyclingArray(不管是什么)对象。

当然,我意识到我可以锁定整个 map ,但这将破坏 ConcurrentMap 的全部意义。

像下面这样的东西在概念上可行吗?

   m.putIfAbsent( key, new Callback<CyclingArray>() {
@Override
public CyclingArray provide() {
return new CyclingArray(); // only called if the key wasn't already present
}
}

您是否知道任何提供 map 的图书馆:

  1. 提供一个类似于 ConcurrentMap 提供的“接口(interface)”,包括一个 putIfAbsent 方法。
  2. 只锁定我们将要使用的段(例如 ConcurrentHashMap 实现)
  3. 允许选择性地创建值,当且仅当 key 不存在时,从而避免无用的垃圾生成。
  4. 不会强制我先使用 containsKey,然后使用 putIfAbsent,因为这也以某种方式违背了 putIfAbsent 的目的。

请注意,我不是询问是否可以使用 ConcurrentMap 完成上述示例(AFAIK 不能)。

我正在考虑扩展 ConcurrentHashMap 并使用回调版本重载 putIfAbsent 但遗憾的是 ConcurrentHashMap 在内部使用了最终的 Segment 类。

在重新发明轮子之前,我想知道是否有任何 map 已经提供了类似的功能。

最佳答案

这是您要查找的常见用例,称为记忆化。我会看看 MapMaker

您将能够创建一个 computingMap 并将您的创建函数放在那里:

 ConcurrentMap<Key, CyclingArray> graphs = new MapMaker()
.concurrencyLevel(32)
.makeComputingMap(
new Function<Key, CyclingArray>() {
public CyclingArray apply(Key key) {
return new CyclingArray(); // only called if the key wasn't already
}
});

只有 Key 不存在时才会调用 Function

而且我知道 Java 的 future 计划有一个 computingMap 类型的接口(interface)将与标准 Java 一起提供,不幸的是,此时您将不得不委托(delegate)给 google-collections。

关于java - 映射允许 putIfAbsent 键已经存在时不创建值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10159124/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com