之前看内存泄露的例子,在JDK1.6版本的String,它的subString()方法可能会造成内存泄露。但是在JDK1.7的版本中,以及修复了。今天在看同事负责模块的代码的时候,偶然看见List这个接口有一个subList()的方法。我就想这个方法是不是肯也会造成内存泄露的问题。我自己用的JDK是1.7的,于是看了看JDK中ArrayList实现subList()的源码。做了一点测试。发现了一个问题。
大家看上面这段JDK代码,可以知道,subList这个方法最后是new了一个SubList返回。但是在newSubList的时候,将自己作为参数传进去了。而SubList是一个内部类,继承了AbstracList<E>,它和String类的构造有异曲同工之妙,String保留的一个char[] 数组,和偏移量,以及大小的属性。在SubList我们也看到了相识的一幕,SubList也有一个AbstracList<E> parent属性,在这相当于String中的char[] 数组。那么ArrayList在这个subList这个截取List的方法里,它将自己的Object[]elementData和新new 的 SubList共享了。那么,它就可能造成内存泄露,而原因就和JDK1.6中的subString的可能造成内存泄露的原因一样了。然后下面是我的测试代码public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex);//<span style="font-family: 宋体;">(代码1)</span> } static void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } private class SubList extends AbstractList<E> implements RandomAccess { private final AbstractList<E> parent; private final int parentOffset; private final int offset; int size; SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { this.parent = parent;//<span style="font-family: 宋体;">(代码2)</span> this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = ArrayList.this.modCount; }
public class TestList { public static void main(String[] args) { List<Person> parentPersonList= new ArrayList<Person>(); for(int i=0;i<5;i++){ parentPersonList.add(new Person("name"+i)); } System.out.println("*************打印父串*****************"); TestList.printf(parentPersonList); List<Person> subPersonList=parentPersonList.subList(2,4);//截取子串 System.out.println("*************打印子串*****************"); TestList.printf(subPersonList); subPersonList.get(1).setName("Name:JoGeen"); System.out.println("*************子串修改后,打印父串*****************"); TestList.printf(parentPersonList); parentPersonList=null; System.out.println("*************父串失去引用,打印子串*****************"); TestList.printf(subPersonList); } public static void printf(List<Person> stringList){ for(Person tempStr:stringList){ System.out.println(tempStr.getName()); } } }
运行结果<pre style="font-family: 宋体; font-size: 12pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">public class Person { private String name; public Person(){} public Person(String name){ this.name=name; } public void setName(String name){ this.name=name; } public String getName(){ return this.name; } }