File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Garbage Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic

Garbage Collection

Arka Sharma
Ranch Hand

Joined: Jun 15, 2011
Posts: 103

I have a class like this
class A{
B b;
C c;

now say in a method I have done

void method()
A a = new A();
a.b = new B();
a.c = new C();
a = null;

at the point i set reference of class A to null the the object of class A will be removed from heap by GC.Also object for class B and C will be removed right ?
Correct me if I'm wrong.


Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Yes since you have no way of accessing them.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

TECHNICALLY, the answer to your question is "No".

At the moment you set A to null, all the objects become ELIGIBLE for GC, but there is no guarantee that they ever will be cleaned up before your program ends.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Garbage Collection
jQuery in Action, 3rd edition