I read some material about Java memory leak. It implements FIFO Queue with array to semantically leak memory. But I don't understand why it will cause memory leak. Is it because it didn't nullify the unused slot in the 'pop' operation? Anyone can explain to me?
queue[head] = null
The FIFO Queue implementation is as follows:
public class FIFOQueue {
private Object[] queue;
private int size = 0, head = 0, tail = 0;
private static final int INITIAL_CAPACITY = 16;
public FIFOQueue() {
queue = new Object[INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
queue[tail] = e;
size++;
tail = increment(tail);
}
public Object pop() throws EmptyStackException {
if (size == 0)
throw new EmptyStackException();
size–;
Object returnValue = queue[head];
head = increment(head);
return returnValue;
}
/** doubling the capacity each time the array needs to grow. */
private void ensureCapacity() {
if (queue.length == size)
queue = Arrays.copyOf(queue, 2 * size + 1);
}
/** make sure the pointers are wrapped around at the end of the array */
private int increment( int x ) {
if( ++x == queue.length )
x = 0;
return x;
}
}