Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Created September 3, 2012 21:16
Show Gist options
  • Save anoopelias/3613635 to your computer and use it in GitHub Desktop.
Save anoopelias/3613635 to your computer and use it in GitHub Desktop.
Test memory leak in java code
import java.util.WeakHashMap;
import junit.framework.Assert;
import org.junit.Test;
public class MemoryLeakTest {
@Test
public void test_stack_memory_leak() {
WeakHashMap<Integer, String> weakMap = new WeakHashMap<Integer, String>();
Stack<Integer> stack = new Stack<Integer>();
Integer i = new Integer(5);
stack.push(i);
weakMap.put(i, i.toString());
i = new Integer(6);
stack.push(i);
weakMap.put(i, i.toString());
i = null;
stack.pop();
stack.pop();
testMap(weakMap);
}
private void testMap(WeakHashMap<Integer, String> weakMap) {
System.gc();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertTrue(weakMap.isEmpty());
}
public class Stack<Item> {
private class Node {
private Item item;
private Node next;
}
private Node front;
public void push(Item item) {
Node oldFront = front;
front = new Node();
front.item = item;
front.next = oldFront;
}
public Item pop() {
Item item = null;
if (front != null) {
item = front.item;
front = front.next;
}
return item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment