1.代码场景
当我们写java程序的时候,不可避免的需要一些集合操作,有时候使用不当,导致GC不能够回收释放被集合占用的内存,例如下面代码
protected List<Map<String, Object>> findListBySql(String sql) {
List<Map<String, Object>> list = this.baseDao.findListBySql(sql);
List<Map<String, Object>> tempList = new LinkedList<Map<String, Object>>();
for (Map<String, Object> map : list) {
Map<String, Object> tempMap;
tempMap = new HashMap<String, Object>();
tempList.add(tempMap);
for (Map.Entry<String, Object> en : map.entrySet()) {
tempMap.put(this.columnToField(en.getKey()), en.getValue());
}
}
return tempList;
}
这个方法是用来查询数据库返回一个listMap的集合,因为数据库的字段和页面字段不完全一致,需要匹配替换,这里替换后的对象是tempList,原来的list对象不再使用,但是内存空间依旧被占用。对于此局部变量不再使用会造成内存泄漏。(即不能被调用也不能被释放)如下面的例子: