I need to get both previous and new value from Java ConcurrentHashMap (in Scala code). To keep it thread-safe I use compute block which returns only new value. Is it possible to get both new and previous value without using var with initial null? Below my current solution:
map: ConcurrentHashMap[String, Object] = new ConcurrentHashMap
def foo = {
var previousValue: Object = null
val newValue = map.compute("key", (_, value) => {
previousValue = Option(value).getOrElse(initialValue)
setNewValue(previousValue)
}
)
(previousValue, newValue)
}
Here is a solution in Java, that you can port.
A somewhat un-contemporary approach; traverse the key-set with a ListIterator.