pythonic
pythonic

Reputation: 21605

Arrays and Garbage collection in Java

Let us say I have an Array a, where the array is of type T. Would setting an element to null mark it for garbage collection.

For example, If I do a[36] = null, or do I need to something more, like also set fields in that object of type T tonull?

Upvotes: 3

Views: 4402

Answers (2)

user1803551
user1803551

Reputation: 13407

As others said, it's hard to tell without the code. However, this might help:

According to Josh Bloch's Effective Java 2nd Edition chapter 2 item 6, you need to set the reference to null in order to allow it to be GC'd if you manage your own memory. He explains that if you don't null a reference it can become an obsolete references and these can cause an OutOfMemoryError.

The example he gives is the following (I'm shortening it). Consider a stack implementation where you can push and pop objects. The problem manifests in the pop operation:

public class Stack {

    private Object[] elements;
    private int size = 0;

    public Object pop() {
        if (size == 0)
            throw new EmptyStackException();
        Object result = elements[--size];
        elements[size] = null; // Eliminate obsolete reference, or you'll have a "memory leak"
        return result;
    }

Note that you're controlling the allocated size manually with the size variable and the GC can't know which elements are allocated and which are free.

Go ahead and read that section in his book for more information if you find it relevant. Your case has similarities to what I wrote, but we can't be sure without code.

Upvotes: 1

Martin McKeaveney
Martin McKeaveney

Reputation: 508

In Java, objects are stored on the heap, whereas variables/references are stored on the stack. The GC performs what is called a 'cycle', which checks which variables no longer refer to actual datatypes, as well as checking if objects are still referred to in the scope. As mario mentioned, an object will eventually be collected when nothing holds a reference to it, however in some performance/memory critical applications, setting objects to null and trying to speed up the garbage collection process has been known to provide marginal performance benefits. In this case, I wouldn't worry about it too much.

Upvotes: 2

Related Questions