gpt4 book ai didi

java - 您是否应该在使用 ConcurrentMap 的 putIfAbsent 之前检查 map 是否包含 key

转载 作者:IT老高 更新时间:2023-10-28 13:51:23 25 4
gpt4 key购买 nike

我一直在使用 Java 的 ConcurrentMap 来制作可以从多个线程中使用的 map 。 putIfAbsent 是一个很好的方法,并且比使用标准映射操作更容易读/写。我有一些看起来像这样的代码:

ConcurrentMap<String, Set<X>> map = new ConcurrentHashMap<String, Set<X>>();

// ...

map.putIfAbsent(name, new HashSet<X>());
map.get(name).add(Y);

在可读性方面这很好,但它确实需要每次都创建一个新的 HashSet,即使它已经在 map 中。我可以这样写:

if (!map.containsKey(name)) {
map.putIfAbsent(name, new HashSet<X>());
}
map.get(name).add(Y);

有了这个改变,它失去了一点可读性,但不需要每次都创建 HashSet。在这种情况下哪个更好?我倾向于支持第一个,因为它更具可读性。第二个会表现得更好,可能更正确。也许有比这两种方法更好的方法。

以这种方式使用 putIfAbsent 的最佳做法是什么?

最佳答案

并发很难。如果您要为并发映射而不是直接锁定而烦恼,那么您不妨试试。确实,不要进行不必要的查找。

Set<X> set = map.get(name);
if (set == null) {
final Set<X> value = new HashSet<X>();
set = map.putIfAbsent(name, value);
if (set == null) {
set = value;
}
}

(通常的stackoverflow免责声明:在我的脑海中。未测试。未编译。等等)

更新: 1.8 增加了computeIfAbsent默认方法为 ConcurrentMap (和 Map 这很有趣,因为该实现对于 ConcurrentMap 来说是错误的)。 (并且 1.7 添加了“钻石运算符”<>。)

Set<X> set = map.computeIfAbsent(name, n -> new HashSet<>());

(请注意,您对 HashSet 中包含的 ConcurrentMap 的任何操作的线程安全负责。)

关于java - 您是否应该在使用 ConcurrentMap 的 putIfAbsent 之前检查 map 是否包含 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3752194/

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