I have a global cache named statisticsCache
which is being modified and read by multiple threads simultaneously. Even after I have applied null check but sometime it throws NullPointerException
in load run. See below for details:
static Map<String, List<Statistics>> statisticsCache = new ConcurrentHashMap<String, List<Statistics>>();
// method to read the global cache
List<Statistics> getStatisticsForQueue(String name) {
List<Statistics> statsCopy = Collections.emptyList();
List<Statistics> statistics = statisticsCache.get(name);
if (statistics != null && !statistics.contains(null)) //Here is the check to avoid NPE but sometimes does not works
statsCopy = new ArrayList<Statistics>(statistics);
return statsCopy;
}
//method to write into global cache
private void setStatisticsListForQueue(String name) {
// flushing all pending Last writes of buckets of a queue to DB
flushStatisticToDB(name);
if (!statisticsCache.containsKey(name)) {
statisticsCache.put(name, new ArrayList<Statistics>(1));
}
List<Statistics> queueStatisticsList = queueServiceMetaDao
.findStatisticsByname(name);
if (queueStatisticsList != null && !queueStatisticsList.isEmpty()) {
for (Statistics statistic : queueStatisticsList) {
// to avoid NPE
if (statisticsCache.get(name).contains(statistic)) {
statisticsCache.get(name).remove(statistic);
}
statisticsCache.get(name).add(statistic);
}
} else {
statisticsCache.put(name, new ArrayList<Statistics>(1));
}
}
//method where I am getting NPE
public long getSize(String name) {
long size = 0L;
List<Statistics> statistics = getStatisticsForQueue(name);
for (Statistics statistic : statistics) {
size += statistic.getSize(); //Sometimes it throws NullPointerException
}
return size;
}
What preventive check should I apply to avoid this?