我有一个像这样的 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/