java - 必须使用 "putIfAbsent"的返回值——真的吗?

标签 java sonarqube

我有一个像这样的 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 没有检测到该方法的副作用在这里对我来说足够了(并且返回值不会添加任何信息)还是我错过了关于 putIfAbsent 契约(Contract)的重要一点?

最佳答案

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 对某些规则非常具有侵入性,因此只需禁用它并继续您的业务。

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

关于java - 必须使用 "putIfAbsent"的返回值——真的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913809/

相关文章:

SonarQube.Scanner.MSBuild.exe : How to specify sonar. 来源?

java - Sonar 插件开发 - 创建全局指标

sonarqube - Upsource 和 SonarQube

java - sonar-project.properties 中的 Glob

java - 持续跟踪用户的位置并绘制他所到之处的路径

java - 表示一个 JSON 数组 - Android SDK

java - 使用 tomcat6 安装 Web 应用程序时出现问题

Java Applet 网络连接

java - 演示 ReadWriteLock 用法的示例

ant - SONAR - 如何排除在 "sonar.test"下定义的包