This refers to an accepted solution to the a question raised in this thread
public void insertOrReplace(String key, String value) {
for (;;) {
String oldValue = concurrentMap.putIfAbsent(key, value);
if (oldValue == null)
return;
final String newValue = recalculateNewValue(oldValue, value);
if (concurrentMap.replace(key, oldValue, newValue))
return;
}
}
I would love to thoroughly understand the code.
I believe putIfAbsent
and replace
altogether can be considered as a compound operation. Is this compound operation atomic without explicit synchronization on object oldValue
? Or just because of the for
loop, it guarantees the atomicity? What exactly does the loop do? Would it cause an infinite loop that makes the method never end?