【发布时间】: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-prs = hashMap.computeIfAbsent(key, k -> createNewInstance());将按预期工作:-)。
标签: java