问题
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