ASA
ASA

Reputation: 1971

Check if computeIfAbsent of ConcurrentHashMap changed something

How do you know that the function computeIfAbsent of a ConcurrentHashMap had to call the given generator method ("mappingFunction")?
From the Javadoc I believe it returns the new value, if one was generated and the old value if one existed. I could set an external flag from a lambda generator function but that would be awkward...

Upvotes: 6

Views: 777

Answers (2)

kapex
kapex

Reputation: 29999

I think using compute is the right way, but checking whether the mappingFunction was called within the compute's remappingFunction may not what be you want. I needed that information outside of the lambda, after compute had finished. I used the old array trick to extract the information out of the lambda.

final var isAbsent = new boolean[1];
instances.compute(keys, (k, value) -> {
    isAbsent[0] = (value == null);
    return Objects.requireNonNullElseGet(value, mappingFunction);
});
if (isAbsent[0]) {
    // entry was absent
}

By the way, if the map contains null values, then the lambda's value parameter can be null even though an entry was present. Calling requireNonNullElseGet ensures that no null values are put into the map here.

Upvotes: 0

assylias
assylias

Reputation: 328737

You could use compute instead:

map.compute(key, (k, v) -> v == null ? /*absent*/ this::getValue : /*present*/ v);

and add some logic to check which branch is called.

Upvotes: 5

Related Questions