Is ConcurrentSkipListMap.compute() safe for relative updates?

225 views Asked by At

The Javadoc for ConcurrentSkipListMap.compute(K, BiFunction) states:

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). The function is NOT guaranteed to be applied once atomically.

I understand that the function may be invoked multiple times, but what does "once atomically" refer to?

Specifically, is it safe for the function to invoke X = X + 1 without the map value getting incremented multiple times?

1

There are 1 answers

13
Stephen C On

It is saying that:

  • the function could be called more than once, and
  • those calls could overlap in time; i.e. if multiple threads are calling compute simultaneously.

In other words, do not expect atomic behavior in the way that the function reference is called by compute.


Specifically, is it safe for the function to invoke X = X + 1 without the map value getting incremented multiple times?

It depends on what mean by "invoke X = X + 1". (You didn't include a clear example ....)

  • If the x = x + 1 means that you are just trying to increment the map's value, then:

    • One call to compute will only result in one "incrementation", because of the definition in the compute in ConcurrentMap.

    • But when you return from compute the value could have been incremented more than once, because another thread was doing the same thing simultaneously.

  • If the x = x + 1 refers to a side-effect of the method reference, then all bets are off:

    • It may have happened multiple times.
    • If your method reference is not properly synchronized, etcetera, there could be all sorts of nasty effects. The spec implies that the compute call is not going to synchronize externally or call the method reference in a mutex or anything like that. Normal concurrency / memory rules apply ...