有没有更好的方法来确定 computeIfAbsent 是否返回了一个新值?

huangapple go评论75阅读模式
英文:

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&lt;String, String&gt; map = new ConcurrentHashMap&lt;&gt;();
AtomicBoolean isNew = new AtomicBoolean(false);
String result = map.computeIfAbsent(&quot;foo&quot;, key -&gt; {
	isNew.set(true);
	return &quot;bar&quot;;
});
result = result + &quot;common op that occurs on both old and new results&quot;;
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(&quot;foo&quot;, key -&gt; {
    // do special stuff here
    return &quot;bar&quot;;
});

huangapple
  • 本文由 发表于 2020年4月4日 21:40:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61028964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定