我有这样的代码:
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.
}
鉴于我的计算方法足够重,我不想创建并立即丢弃不需要的计算值,是否有更漂亮的方法来做到这一点?
编辑:我也担心我的代码将如何处理线程。如果 2 个线程尝试计算同一个键,我认为它们最终可能都报告 isNew 为 true。
最佳答案
您可以在 computeIfAbsent
中使用逻辑lambda - 只有在必须计算新值时才会执行它:
String result = map.computeIfAbsent("foo", key -> {
// do special stuff here
return "bar";
});
关于java - 有没有更好的方法来确定 computeIfAbsent 是否返回了新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61028964/