package com.design.memory;
import java.util.EmptyStackException;
/**
@Author H.W
@createTime 2013-12-11 上午10:10:54
**/
public class OutofMeoryStack {
private int size;
private Object[] elememnts;
public OutofMeoryStack(int initalCapacity){
this.elememnts = new Object[initalCapacity];
}
public void push(Object e){
ensureCapacity();
elememnts[size ++] = e;
}
public Object pop(){
if(size == 0){
throw new EmptyStackException();
}
return elememnts[-- size];
}
private void ensureCapacity(){
if(elememnts.length == size){
Object[] oldObjects = elememnts;
elememnts = new Object[2 * elememnts.length + 1];
System.arraycopy(oldObjects, 0, elememnts, 0, oldObjects.length);
System.out.println(size);
}
}
public static void main(String[] args) throws InterruptedException{
OutofMeoryStack outofMeoryStack = new OutofMeoryStack(100);
for(int i = 0;i < 5;i ++){
for(int j = 0;j < 100000;j ++){
outofMeoryStack.push(new TestEntity());
}
for(int j = 0;j < 100000;j ++){
outofMeoryStack.pop();
}
}
System.out.println("执行结束");
System.gc();
Thread.sleep(10 * 1000);
System.out.println(outofMeoryStack.size);
}
}
读了effective java中的一段,把这段代码真正敲进去执行了一遍,监视工具用的是jProfiler;最后的120秒是为了让GC有足够的时间去回收及让我截图。TestEntity是一个简单的测试类,主要是在jProfiler里方便查找对象,不用纠结。
下图就是结果:
当我将pop方法改为
public Object pop(){
if(size == 0){
throw new EmptyStackException();
}
elememnts[size - 1] = null;
return elememnts[-- size];
}
结果是这样
后来我测试了下,执行push而不执行pop操作的次数也就是最终泄露的对象个数。