我有这样的代码:
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.
}
鉴于我的计算方法足够繁重,我不想创建并在不需要时立即丢弃计算值,是否有更漂亮的方法来执行此操作?
编辑:我还担心我的代码处理线程的能力如何。 如果两个线程尝试计算相同的密钥,我认为它们最终可能都会报告 isNew 为 true。
您可以将逻辑放在
computeIfAbsent
lambda 中 - 仅当必须计算新值时才会执行它:
String result = map.computeIfAbsent("foo", key -> {
// do special stuff here
return "bar";
});
我认为除了通过
AtomicBoolean
进行沟通之外,没有更好的方法了。但是,您对 AtomicBoolean
s API 的使用可以改进:
AtomicBoolean
的构造函数,无参数构造函数会做正确的事情。lazySet
(释放语义)和 getAcquire()
(获取语义)在某些内存模型较弱的架构上获得较小的性能优势。ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
AtomicBoolean isNew = new AtomicBoolean();
String result = map.computeIfAbsent("foo", key -> {
isNew.lazySet(true);
return "bar";
});
result = result + "common op that occurs on both old and new results";
if (isNew.getAcquire()) {
// op that occurs only on new results. Must occur after common op.
}