必须使用 "putIfAbsent" 的 return 值 - 真的吗?

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

我有一个像这样的 ConcurrentMaps 的 ConcurrentMap...

ConcurrentMap<String, ConcurrentMap<K, V>> mapsMap = new ConcurrentHashMap<>();

现在在某些方法中,我想通过确保某个键存在映射来防止 NPE...

 mapsMap.putIfAbsent(someKey, new ConcurrentHashMap<K, V>());

...所以我可以安全地调用...

 mapsMap.get(someKey).put(...);

...这里不用担心空值。

现在,Sonarqube 告诉我,这违反了规则 RSPEC-2201...

Return values from functions without side effects should not be ignored [..] and also on ConcurrentMap.putIfAbsent calls ignored return value.

这只是 SonarQube 没有检测到该方法的副作用对我来说已经足够了吗(return 值不会添加任何信息),还是我错过了关于 putIfAbsent 合同的重要一点?

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.

如果不需要返回值,您可以安全地忽略它。
Sonarqube 对某些规则非常具有侵入性,因此只需禁用它并继续您的业务。

恕我直言,该特定规则主要是为代码由多个开发人员编写的项目中的常见模式设置的。

除了@LppEdd 的正确答案外,这个问题也在声纳论坛上answered

基本上,这条规则取自 FindBugs 的规则 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.

在这种情况下,我不保留对存储值的引用,这确实是误报。

此特定规则很可能在将来作为单独的规则在 SonarQube 中实施,而不是作为当前规则 (RSPEC-2201) 的一部分。