英文:
Is there a better way to determine if computeIfAbsent returned a new value?
问题
我有类似这样的代码:
ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
AtomicBoolean isNew = new AtomicBoolean(false);
String result = map.computeIfAbsent("foo", key -> {
isNew.set(true);
return "bar";
});
result = result + "在旧结果和新结果上都会发生的常见操作";
if (isNew.get()) {
// 仅在新结果上发生的操作。必须在常见操作之后发生。
}
考虑到我的计算方法足够复杂,我不想在不需要时创建并立即丢弃计算出的值,是否有更好的方式来完成这个操作?
编辑:我还担心我的代码在多线程情况下会有什么问题。如果有2个线程尝试计算相同的键,我认为它们可能都会对isNew报告为true。
英文:
I've got code like this :
ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
AtomicBoolean isNew = new AtomicBoolean(false);
String result = map.computeIfAbsent("foo", key -> {
isNew.set(true);
return "bar";
});
result = result + "common op that occurs on both old and new results";
if (isNew.get()) {
// op that occurs only on new results. Must occur after common op.
}
Is there a prettier way to do this given that my compute method is heavy enough that I don't want to create and the immediately discard computed values if they aren't needed?
Edit: I'm also worried how well my code will cope with threading. If 2 threads try to compute for the same key I think they might both end up reporting true for isNew.
答案1
得分: 2
你可以将逻辑直接放在 computeIfAbsent
的 lambda 表达式中 - 只有在需要计算新值时才会执行:
String result = map.computeIfAbsent("foo", key -> {
// 在这里执行特殊操作
return "bar";
});
英文:
You could just have the logic in the computeIfAbsent
lambda - it will only be executed if a new value has to be computed:
String result = map.computeIfAbsent("foo", key -> {
// do special stuff here
return "bar";
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论