我有一個名爲statisticsCache
的全局緩存,它正在被多個線程同時修改和讀取。即使在我申請了空檢查但是有時它會在加載運行中拋出NullPointerException
。詳見下文:在多線程環境中儘管空檢查得到NullPointerException
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;
}
我應該採用什麼預防性檢查來避免這種情況?
可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how -do-i-fix-it) –
嘗試'size + = statistic.getSize()== null? 0L:statistic.getSize()' – Ian2thedv
大小很長,但不長。如此統計。getSize()== null將永遠爲假, – Laxmikant