I have a simple question about Java GC. Some example :
Object instance = new Object();
longMethod(instance);
...
// First example
private void longMethod(Object arg) {
Thread.sleep(1000 * 60 * 60)
// this method works 1hr. Does it keep reference to Object and GC canot release it?
}
//Seconde example
private void longMethod(Object arg) {
arg = null;
Thread.sleep(1000 * 60 * 60)
// we clear reference in method. Can GC relese Object now?
}
So what is lifecycle of "instance" in both cases? Thanks.
In both cases Object instance
, which is a local variable of the method that calls longMethod
, holds a reference to the instance, so the GC can't release it before the method that called longMethod
ends.
Note that arg = null
only sets the local reference inside longMethod
to null. It doesn't change the value of the instance
variable in the method that called longMethod
.
Java is pass-by-value: setting the local variable arg
in the second method to null does not mean that the local variable in the caller method is also set to reference null. Therefore, the object in the caller still has a reference pointed to it.
Consider the case where you create a new object inside the method:
private void longMethod(Object arg) {
arg = new Object(); // Line 1
Thread.sleep(1000 * 60 * 60);
arg = null; // now the object created in line 1 is eligible for GC
}
In this case, the object created using arg = new Object();
(which is different than the one created in the caller method) is eligible for GC.
And consider the case where you have this in the caller method:
Object instance = new Object(); // Line 1
longMethod(instance);
instance = null; // now the object created in line 1 is eligible for GC (see note below)
Now the object previously created in Line 1 is also eligible for GC assuming there are no references to the object that were created inside longMethod
.
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