Member-only story
Effective Java! Don’t Leak Object References!
Today our topic is about memory leaks inside of Java. Wait!? Memory leaks in Java? That’s not possible right? Isn’t that one of the promises of Java, to have managed memory? When I started learning to code I started with C++ like man people. Let me tell you something, if you don’t manage your memory well in C++ you will likely blow your foot off. But anyway we were talking about memory leaks in Java. I think the best way to show this is with an example and I think the example from the book is a great example of it:
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_SIZE = 16; public Stack() {
elements = new Object[DEFAULT_INITIAL_SIZE];
} public void push(Object element) {
ensureCapacity();
elements[size++] = element;
} public Object pop() {
if (size == 0) {
throw new EmptyStackException();
}
return elements[--size];
} private void ensureCapacity() {
if(elements.length = size) {
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
}
Looks like it would work right? I’ll let you in on a secret. This code does actually work fine but it does have a “memory leak”. Can you spot it? I for one definitely didn’t get it right off the bat. The problem lies in this line here from our pop
function.:
return elements[--size];