Delete object's variable after instantiation

306 views Asked by At

So I have an object which needs certain variables to be instantiated. These variables are passed to the object through an array of objects. Then, each element in the array gets assigned to an internal variable.

Does this array get garbage collected after the internal variables are assigned and the array is never referenced again, or should it be manually done?

class MyObject () {
    public static Object [] values;
    public void setvalues(inputArray) {
        values = inputArray;
    }
}

Memory is kind of important because I need to create a few hundred of these objects plus the rest of the code.

2

There are 2 answers

1
Sweeper On BEST ANSWER

Whether the array is eligible for GC depends on this condition:

  • Is there anything still referencing the array?

If, you have something like this:

public class Foo {
    private int[] myArray = {1, 2, 3, 4};
    YourObject obj;

    public void someMethod() {
        obj = new YourObject(myArray);
    }
}

Then myArray is not eligible for garbage collection because the variable myArray in the Foo object is still referencing it. You can then set myArray to null to make it eligible for GC.

If myArray were a local variable, however:

public class Foo {
    YourObject obj;
    public void someMethod() {
        int[] myArray = {1, 2, 3, 4};
        obj = new YourObject(myArray);
    }
}

Then it is eligible for GC after someMethod returns because myArray will have gone out of scope by then.

Also, note that "eligible for GC" doesn't mean "will be collected immediately". It just mean that the GC has a possibility of collecting it in the future. When exactly? We don't know.

0
Prashant On

I am assuming your code looks like this

//Client class
o.setValues(arrayOfObjects);
//In the receiving object
public void setValues (Object[] objects){
 // Dostuff
}

Two things need to happen for arrayOfObjects to be a candidate for GC -

  1. arrayOfObjects needs to go out of scope. OR
  2. arrayOfObject needs to be assigned another value or null.

If you are really concerned about memory, I would surmise it's the contents of the array that need to be garbage collected, not the array itself. The contents will clearly be referenced by the receiving object, so they will not be garbage collected. Hope this helps.