The return value of "putIfAbsent" must be used - really?

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

You can safely ignore the returned value, if you don't need it.
Sonarqube is pretty invasive with certain rules, so just disable it and go on with your business.

Imho, that specific rule is mostly set for common patterns on a project where code is written by multiple developers.


In addition to the correct anser by @LppEdd, this question was also answered over at the sonarqube forums:

Basically, this rule was taken from FindBugs' rule RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED

The putIfAbsent method is typically used to ensure that a single value is associated with a given key (the first value for which put if absent succeeds). If you ignore the return value and retain a reference to the value passed in, you run the risk of retaining a value that is not the one that is associated with the key in the map. If it matters which one you use and you use the one that isn't stored in the map, your program will behave incorrectly.

As in this case, I do not retain a reference to the value stored, this would indeed be a false positive.

It is likely that this specific rule will be implemented as a seperate rule in SonarQube in the future and not as part of the current rule (RSPEC-2201) anymore.

Tags:

Java

Sonarqube