is there a replacement for while loop for update of concurrentMap with scala TrieMap

£可爱£侵袭症+ 提交于 2020-01-06 14:11:15

问题


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;
    }
}

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?


回答1:


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!

Addendum

Rather than add another comment, I'll put the new information here...

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!



来源:https://stackoverflow.com/questions/21286823/is-there-a-replacement-for-while-loop-for-update-of-concurrentmap-with-scala-tri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!