Atomicity of pooled putIfAbsent and ConcurrentMap replacement

This refers to the accepted solution to the issue 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 like to fully understand the code.

I believe that putIfAbsent

, and replace

in general can be seen as an integral operation. Is this compound operation an atom without explicit synchronization on the object oldValue

? Or just because of the loop for

, does this guarantee atomicity? What exactly does a loop do? Could this cause an endless loop that causes the method to never end?

+3


source to share


1 answer


First of all, the original question introduces some fancy code. Not sure if this is good, but let's leave that aside.

Secondly, the selected answer and the one you copied here is just another way to do the same code as in the question.

So what this (fancy) method does:

  • Checks if a key is mapped to a value and does not assign a value and exists.
  • If so, recalculate the value and replace the old value.


Why do we need a loop? Cause if 2 threads recalculate the value and replace "together", only 1 will succeed and therefore will return from the method. "Losing" the thread will need to go through the process again. It will probably get a new value in the call putIfAbsent

and recalculate the new value for replacement, this time might be OK.

A few notes:

  • I would recommend carefully reading the method APIs ConcurrentMap

    putIfAbsent

    and replace

    .
  • In reality, there is a corner case (which will never happen) that a call to this method will be stuck forever, because it will always be "lost" for another call.
  • I suspect that keeping this whole method in sync would be best to avoid all those cumbersome loops. But since I do not quite understand what this code is trying to solve, I cannot officially state this.
0


source







All Articles