Reputation: 51
How does the Java GC work on a simple situation like this:
ArrayList<Object> list = new ArrayList<>();
list.add(new Object());
list.add(new Object());
//do something with objects
list.remove(0);
Upvotes: 1
Views: 50
Reputation: 4074
First off: the class Object
is not an "unnamed class". If at all, one would use this term in the context of anonymous classes.
GC retains all objects that are alive, i.e. reachable from GC roots. All other objects are discarded. Local variables are (among others) GC roots.
What you are describing is a situation where there is no reference variable pointing directly to your object, like for instance Object myObj = new Object();
.
However, there is a list containing a reference to your object.
Now, what would happen if the GC were to run?
Before list.remove(0);
your object would be marked as alive since it is
indirectly reachable through the list.
After list.remove(0);
(and assuming "do something with objects"
doesn't involve establishing another reference to your object) your
object wouldn't be marked as alive by the GC since it is not reachable
anymore. The memory that was occupied by your object would afterwards be
marked as free.
Upvotes: 1
Reputation: 4112
Well typically if use use the object in the "do something with objects" that causes them to be retained then they will not be garbage collected despite the list.remove
call.
Also try and make sure you declare the list
in the shortest scope possible. That is closest to where it is being used. That would make the list automatically fall out of scope and be GC'd earlier.
Also sometimes you may want to set the object to null after you are done using it. That as well works to get it off scope and eligible for GC.
Upvotes: 1