permaculture playing cards
The moose likes Beginning Java and the fly likes eligible for garbage collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "eligible for garbage collection" Watch "eligible for garbage collection" New topic

eligible for garbage collection

joel garner

Joined: Dec 28, 2008
Posts: 9
How do we know which object is eligible for garbage collection ?
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46397
What do you know about it? Have you searched anywhere? Do you have a specific question, for an exam for example?
Ulises Pulido
Ranch Hand

Joined: Jul 24, 2008
Posts: 81

It is eligible when the object reference get lost and the object is abandoned in the dark side of the heap memory.

By reference I mean that there is no variable pointing to that object. Usually we call them variables but I prefer the term reference because its easier to understand how this things work.

A code sample could be this:

public void method() {
Object a = new Object();

after finishing the method no reference will be pointing to the object a was pointing to and that "new Object();" will be abandoned, sad but true.

In case that you return it.

void aMethod() {
Object a = anotherMethod();

Object anotherMethod() {
Object b = new Object();
return b;

In this case the Object created "new Object()" will have two references pointing to it, first b whose reference is returned in the method and assigned to a, then a will be pointing to that "new Object()" as well, the reference of b dissapears, the aMethod gets executed and the reference from a to "new Object()" dissapears as well and this object gets abandonded and now eligible for garbage collection.

I hope this helps a little.

SCJP 5.0, SCWCD 5.0, SCBCD 5.0, SCJD, SCEA in progress
joel garner

Joined: Dec 28, 2008
Posts: 9
Thanks for the reply ulises pulido.
I agree. Here's the link:
subject: eligible for garbage collection
It's not a secret anymore!