Is there a better way to determine if computeIfAbsent returned a new value?

Viewed 212

I've got code like this :

ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
AtomicBoolean isNew = new AtomicBoolean(false);
String result = map.computeIfAbsent("foo", key -> {
    isNew.set(true);
    return "bar";
});
result = result + "common op that occurs on both old and new results";
if (isNew.get()) {
    // op that occurs only on new results.  Must occur after common op.
}

Is there a prettier way to do this given that my compute method is heavy enough that I don't want to create and the immediately discard computed values if they aren't needed?

Edit: I'm also worried how well my code will cope with threading. If 2 threads try to compute for the same key I think they might both end up reporting true for isNew.

1 Answers

You could just have the logic in the computeIfAbsent lambda - it will only be executed if a new value has to be computed:

String result = map.computeIfAbsent("foo", key -> {
    // do special stuff here
    return "bar";
});
Related