是有更换while循环更新concurrentMap与scala TrieMap [英] is there a replacement for while loop for update of concurrentMap with scala TrieMap
问题描述
在java中,我可以使用以下命令:
In java I'm use to do following:
boolean done = false;
while(!done) {
Long oldValue = map.putIfAbsent(key, 1L);
if(oldValue != null) {
done = map.replace(key, oldValue, oldValue + 1);
} else {
done = true;
}
}
现在我看到在scala使用 TrieMap
(如果我坚持可变的版本)我真的不明白如果有一个单击操作已经存在这个 TrieMap <
now i see that in scala I'm better off using TrieMap
(if i insist on the mutable version) i don't really understand if there is a one shot operation already exists in this TrieMap
which will do this while loop for me, if yes can you please show an example?
推荐答案
请小心与 TrieMap
(至少是可变的),它实际上不是线程安全。至少,它继承了 getOrElseUpdate
的非线程安全实现。我没有检查其他方法(例如 putIfAbsent
)是否有相同的问题,但是一个并发错误是足够糟糕的!
Be careful with TrieMap
(at least the mutable one), it's not actually thread safe. At a minimum, it inherits a non-thread-safe implementation of getOrElseUpdate
. I did not check whether other methods (such as putIfAbsent
) have the same problem, but one concurrency bug is bad enough!
附录
不要添加其他评论,我将把新信息放在这里...
Rather than add another comment, I'll put the new information here...
TrieMap.putIfAbsent
有一个 TrieMap
特定实现,但其值参数不是一个by-name参数,因此如果缓存的目的是避免昂贵的计算,它会再次失败!
TrieMap.putIfAbsent
has a TrieMap
-specific implementation but its value parameter is not a by-name parameter, so if the purpose of the cache is to avoid expensive computations, it fails again!
这篇关于是有更换while循环更新concurrentMap与scala TrieMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!