HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Can not clearing a local java.util.Vector cause a memory leak?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
localcanutiljavaclearingleakmemorycausenotvector

Problem

In the code below, does not clearing or setting the local variable completed to null create the potential for a memory leak?

private Vector elements;

private void update()
{
    Vector completed = new Vector();
    for( Element e : elements )
    {
        if( e.isComplete() )
        {
           completed.add( e );
        } else {
           e.update();
        }
    } 

    elements.removeAll( complete );
}


Should I add complete.clear() before the update() method exits?

The elements Vector is an instance variable on a class that is populated with Element objects elsewhere in the program.

Solution

Because complete is used and is referenced entirely within the context of the method update(), it will become unreferenced after the method returns.

This will eventually cause it to be garbage collected.

After it has been garbage collected, some or all of the elements that belong to it will also become unreferenced and then garbage collected.

So technically, no, it is not necessary to call complete.clear().

On the other hand, getting into the habit of insuring that things are properly cleaned up can be important in other circumstances. As such, it would not be wrong to add the clear() call to the end of the method. To do so, or not do so could be either a stylistic choice, or something to consider addressing in a coding standards document. I would probably add it myself.

Context

StackExchange Code Review Q#14963, answer score: 3

Revisions (0)

No revisions yet.