gpt4 book ai didi

java - 以原子方式确保 ConcurrentMap 条目

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:28:10 24 4
gpt4 key购买 nike

在 Java 中,我经常需要懒惰地获取 ConcurrentMap 的条目,仅在必要时才创建。

例如我可能有

ConcurrentMap<String, AtomicReference<Something>> a = new ConcurrentHashMap<>();
ConcurrentMap<String, Something> b = new ConcurrentHashMap<>();

我想创建一个通用函数来完成这项工作,这样我就不会重复自己 the rather cumbersome double checking code对于每种类型。

以下是我所能得到的:

<K, V, C extends V> V ensureEntry(ConcurrentMap<K, V> map, K key, Class<? super C> clazz) throws Exception {
V result = map.get(key);
if (result == null) {
final V value = (V)clazz.newInstance();
result = map.putIfAbsent(key, value);
if (result == null) {
result = value;
}
}
return result;
}

然后我可以像这样使用它:

AtomicReference<Something> ref = ensureElement(a, "key", AtomicReference.class);
Something something = ensureElement(b, "another key", Something.class);

问题是:该函数很脏,并且仍然有一个不安全的泛型类转换((V))。一个完全通用和更清洁的可能吗?也许在 Scala 中?

谢谢!

最佳答案

对于 Java 8 lambda,以下是我能得到的最简单的......

<K, V> V ensureEntry(ConcurrentMap<K, V> map, K key, Supplier<V> factory) {
V result = map.get(key);
if (result == null) {
V value = factory.get();
result = map.putIfAbsent(key, value);
if (result == null) {
result = value;
}
}
return result;
}

ConcurrentMap<String, AtomicReference<Object>> map = new ConcurrentHashMap<>();
ensureEntry(map, "key", () -> new AtomicReference<>());
// or
ensureEntry(map, "key", AtomicReference::new);

关于java - 以原子方式确保 ConcurrentMap 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18568190/

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