Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sonarqube

i've got a ConcurrentMap of ConcurrentMaps like this...

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

Now in some method, I would like to prevent NPE by making sure a map exists for a certain key like this...

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

...so I can safely call stuff like...

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

...without worrying about null values here.

Now, Sonarqube is telling me, that this violates the rule RSPEC-2201...

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

Is this just SonarQube not detecting that the side effect of the method is enough for me here (and the return value would not add any information) or am I missing an important point about the putIfAbsent contract?

like image 205
Florian Schaetz Avatar asked Feb 27 '19 20:02

Florian Schaetz


People also ask

What is putIfAbsent in Java?

The Java HashMap putIfAbsent() method inserts the specified key/value mapping to the hashmap if the specified key is already not present in the hashmap. The syntax of the putIfAbsent() method is: hashmap.putIfAbsent(K key, V value) Here, hashmap is an object of the HashMap class.

Can putIfAbsent return null?

The putIfAbsent(Key, value) method of Hashtable class which allows to map a value to a given key if given key is not associated with a value or mapped to null. A null value is returned if such key-value set is already present in the HashMap.

Why putIfAbsent?

Overview. The putIfAbsent method adds the key-value pair to the map if the key is not present in the map. If the key is already present, then it skips the operation.


Video Answer


1 Answers

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.

like image 52
LppEdd Avatar answered Oct 05 '22 08:10

LppEdd