【发布时间】:2015-12-02 11:58:14
【问题描述】:
我有一个名为statisticsCache 的全局缓存,它正在被多个线程同时修改和读取。即使我应用了空检查,但有时它会在负载运行中抛出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;
}
我应该应用什么预防性检查来避免这种情况?
【问题讨论】:
-
试试
size += statistic.getSize() == null ? 0L : statistic.getSize() -
尺寸很长但不是很长。所以 statistic.getSize() == null 将永远是错误的,
标签: java multithreading concurrency nullpointerexception