I'm maintaining multi-threaded legacy code that uses ConcurrentHashMap
.
There are operations of add and remove in other methods.
In the following code, at some point after collecting few values from the map, it throws NullPointerException
when executing synchronize(value)
.
public class MyClass{
private final Map<MyObj, Map<String, List<String>>> conMap = new ConcurrentHashMap<>();
//...
public void doSomthing((MyObj id){
List<Map<String, List<String>>> mapsList = new LinkedList<>();
for(MyObj objId: conMap.keySet()){
if(objId.key1.equals(id.key1)){
mapsList.add(conMap.get(objId));
}
}
for(Map<String, List<String>> map: mapsList){
synchronized(map){ // <-- NullPointerException here
//...
}
}
//...
}
I have a feeling that maybe during the iteration in the first loop, records are being remove. And when the line:
mapsList.add(conMap.get(objId));
being executed, objId
no longer exist and mapsList
adding null and as a result, during the second loop NullPoinerException
is thrown.
Is there any other reason to get this exception?