
package com.code.revisited.memoryleaks; import java.util.Iterator; import java.util.NoSuchElementException; /** * @author sureshsajja * */ public class Stack<E> implements Iterable<E> { private int N; private E[] array; @SuppressWarnings("unchecked") public Stack(int capacity) { array = (E[]) new Object[capacity]; } @Override public Iterator<E> iterator() { return new StackIterator(); } private class StackIterator implements Iterator<E> { private int i = N - 1; @Override public boolean hasNext() { return i >= 0; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } return array[i--]; } @Override public void remove() { throw new UnsupportedOperationException(); } } public void push(E item) { if (isFull()) { throw new RuntimeException("Stack overflow"); } array[N++] = item; } public E pop() { if (isEmpty()) throw new RuntimeException("Stack underflow"); E item = array[--N]; return item; } public boolean isEmpty() { return N == 0; } public int size() { return N; } public boolean isFull() { return N == array.length; } public E peek() { if (isEmpty()) throw new RuntimeException("Stack underflow"); return array[N - 1]; } }
类com.code.revisited.memoryleaks.StackTest用于执行栈操作。要进行入栈及出栈10000次操作,理想是入栈时分配堆内存,出栈后对象被回收。
package com.code.revisited.memoryleaks; /** * @author sureshsajja * */ public class StackTest { /** * @param args */ public static void main(String[] args) { Stack<Integer> s = new Stack<Integer>(10000); for (int i = 0; i < 10000; i++) { s.push(i); } while (!s.isEmpty()) { s.pop(); } while (true ) { // do something } } }
package com.code.revisited.memoryleaks; /** * @author sureshsajja * */ public class StackTest { /** * @param args */ public static void main(String[] args) { // Stack<Integer> s = new Stack<Integer>(10000); // for ( int i = 0; i < 10000; i++) { // s.push(i); // } // // while (!s.isEmpty()) { // s.pop(); // } while (true ) { // do something } } }
把栈操作的设为1号,没有栈操作的设置为2号,分别生成Heap Dump文件,我们看一下类实例的截图:

