When i do the following:
public double[] someFn()
{
double[][] b = new double[5][5];
return b[2];
}
is the rest of buffer b ready for the trashbin or does the still somewhere in-use ref to the 2nd row stop the whole array b from getting collected?
As im talking 'bout generic arrays, i cant test for finalization…
Yes, each element of b is just a reference to a double[]. Each one can be a reference to an independent object - or several elements could refer to the same array, or have null values.
There's no "backlink" from the element to the array containing it.
Basically, you should think of "multidimensional" arrays as just normal arrays where the element type happens to be another array. So for example:
String foo() {
String[] array = getStrings();
return array[0];
}
The string reference returned by the method doesn't know anything about the array, and nor does the string object it refers to. It's exactly the same way with arrays of arrays.
The other elements of b will ready to be gc-ed after someFn() returns,because you can't get any references of them. I wrote a small program to prove that:
public class GCDemo {
static class OneMB {
byte[] data = new byte[1024 * 1024];
String name;
public OneMB(String name) {
this.name = name;
}
protected void finalize() throws Throwable {
System.out.println(name + " gc-ed");
}
}
public static OneMB[] someFn() {
OneMB[][] b = new OneMB[3][3];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j] = new OneMB(i + "-" + j);
}
}
return b[2];
}
public static void main(String[] args) throws InterruptedException {
OneMB[] b2 = someFn();
System.gc();
System.gc();
Thread.sleep(6000);
System.out.println("after b2 is released");
b2 = null;
System.gc();
Thread.sleep(2000);
}
}
the output is
0-2 gc-ed
1-2 gc-ed
1-1 gc-ed
0-1 gc-ed
0-0 gc-ed
1-0 gc-ed
after b2 is released
2-2 gc-ed
2-1 gc-ed
2-0 gc-ed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With