Java – does referencing array indexes cause memory leaks?

I'm reading "item 6: eliminating obsolete object references" in the second edition of effective Java

The following is a code snippet

//Can you spot the "memory leak"?
public class Stack {
    private Object[] elements;
    private int size = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    public Stack() {
        elements = new Object[DEFAULT_INITIAL_CAPACITY];
    }

    public void push(Object e) {
        ensureCapacity();
        elements[size++] = e;
    }

    public Object pop() {
        if (size == 0)
            throw new EmptyStackException();
        return elements[--size];
    }

    /**
     * Ensure space for at least one more element,roughly doubling the capacity
     * each time the array needs to grow.
     */
    private void ensureCapacity() {
        if (elements.length == size)
            elements = Arrays.copyOf(elements,2 * size + 1);
    }
}

According to this project, the memory leak is due to the fact that the array index is not referenced as null after the pop-up, as shown below:

public Object pop() {
    if (size == 0)
        throw new EmptyStackException();
    Object result = elements[--size];
    elements[size] = null; // Eliminate obsolete reference
    return result;
}

My understanding is that for a given array, I have completed the element [0] = new object(), and then I execute this element [0] = new object() again, and then my first object will be eligible for garbage collection because 0th my array index no longer points to it

Is my understanding incorrect? If it is correct, how does it appear as a memory leak in effective Java

Solution

You got most of it

If you do this:

elements[0] = someOtherObject;

Then another element stored in index 0 is no longer referenced and may be collected

But the first pop () implementation retains this reference - it only reduces the "counter" of the storage element Therefore, the object is still referenced – and will not be collected until a new object is added to the stack!

Because the comments in the second version of Pop () make it clear that references must be eliminated to ensure that the stack does not retain references to the object The object should be popped - so the stack should not retain knowledge about the deleted object!

And confirm the submission: Yes, when one pushes n objects and then n other objects, then you have no memory leakage - because the underlying array references will be updated and point to the new object Yes, if fewer than n objects are pushed after pop-up, obsolete references will be retained and garbage collection will be blocked

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>