I know this question has been asked several times, but I didn't find any right answer for the question. How do you avoid NullPointerException from being thrown when you fetch results from a ConcurrentHashMap. I have the below code that is throwing me a NullPointer.
public static String getPersonInfo(String personAddress) {
//if(concMap!=null && concMap.containsKey(personAddress))
return concMap.get(personAddress);
//return null;
}
In the concurrent hashmap,I am storing person id and address in a concurrent hashmap. In a few cases, the id is null. Although I do a null check before putting the data in the map, I still get the below error while trying to read the data.
java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.get(Unknown Source)
Someone please help :( I have wasted over 3 hours trying to debug this. Although I see a lot of posts online, I am not very clear yet with what can be done to avoid it.
Do a null check on personAddress, calling get(null) throws a NPE. It's even specified in the method documentation
It's the key that is null, which in this case is personAddress (as everyone is saying). However, it would be safest to check them all:
public static String getPersonInfo(String personAddress) {
if (personAddress != null && concMap != null && concMap.containsKey(personAddress)) {
return concMap.get(personAddress);
}
return null;
}
I should add that the ability for almost everything but primitives to be null is a common headache in Java. Most internal methods don't even bother dealing with it and just throw the NPE. If something can't be null down the road, check for this at your first meaningful opportunity..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With