Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Is The Object Eligible For Garbage Collection?

In the code below, given that amethod has been called. At what point/line is the Object originally referenced by myObject, eligible for Garbage Collection?

class Test {
  private Object classObject;

  public void amethod() {
    Object myObject = new Object();
    classObject = myObject;
    myObject = null;
  }
}

And if classObject or amethod had an access modifier of public, protected, default or static, would it affect what point the Object is eligible for Garbage Collection? If so, how would it be affected?

  • My first thought is that the Object is eligible for Garbage Collection when the Test object is eligible for Garbage Collection.
  • But then again. The optimizer may know that the classObject is never read from in which case classObject = myObject; would be optimized out and myObject = null; is the point it is eligible for Garbage Collection.
like image 886
Dorothy Avatar asked Oct 30 '12 17:10

Dorothy


People also ask

When an object does become eligible for garbage collection in Java?

When an object created in Java program is no longer reachable or used it is eligible for garbage collection.

When an object is eligible for garbage collection in C#?

Closed 9 years ago. where it says as soon as you pass the line of code where a variable is last used, the object referenced by it is eligible for garbage collection (That is if no other variable holds a reference to that object).

How many items are eligible for garbage collection?

as per the answer given for this question, there is no object eligible for GC at line 11; but according to me at least one object, t2, which is set to point null at line 6, should be eligible for garbage collection.

Is null eligible for garbage collection?

SO no, GC will never remove nulls from an array. That's not what it does. Besides which, a null value in an array is perfectly valid and removing it would break many programs.


1 Answers

The object will not become a candidate for garbage collection until all references to it are discarded. Java objects are assigned by reference so when you had

   classObject = myObject;

You assigned another reference to the same object on the heap. So this line

   myObject = null;

Only gets rid of one reference. To make myObject a candidate for garbage collection, you have to have

  classObject = null;
like image 125
kolossus Avatar answered Oct 08 '22 00:10

kolossus