File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Performance 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 » Performance
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic

Garbage Collection

Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 370

I have come across some code in our application:

I have asked the developer why it's there and why he doesn't just use collection = null, his answer is that calling = null will leave the objects in the collection stuck and they won't be garbage collected thus causing a memory leak. Can someone confirm if this is true? I always thought that if objecta references objectb but objecta is not referenced then both would be garbage collected.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

No, it's false. You are correct.

However... it's also worth noting that setting the collection parameter to null is pointless. Since parameters are passed by value, this doesn't set the original variable which was passed to the method to null anyway. Perhaps that is the real reason why the collection doesn't actually get garbage collected.
susha bhogs

Joined: Mar 29, 2006
Posts: 6
It seems the developer is right. Because when we passed the objects - at the JVM its by reference only. Also, collection passes it by reference [similar to shallow cloning]

I agree. Here's the link:
subject: Garbage Collection
It's not a secret anymore!