• Post Reply Bookmark Topic Watch Topic
  • New Topic

GC of objects inside Collection

 
veerabahu Subramanian
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone clarify, Is the objects inside a collections are "guaranteed" to GC when the collection goes out of the scope. For example


This goes back a long way in the call stack and will be used. Now my doubt is
1. Will the and the 1000 gets GC once collObj goes out of scope.

2. Will the and the 1000 gets GC once collObj is made to NULL
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, GC is generally not guaranteed to happen on any object. If you have plenty of heap left, Java may decide not to waste time doing GC. The only time that GC is guaranteed to happen is if the heap would otherwise be exhausted; you won't get an OutOfMemoryError when there are objects that could be GCd (*)

It is better to talk about objects becoming eligible for GC, as this happens at a known time, whereas GC itself happens at an unknown later time, if at all.

In your posted code, it is not possible to say whether any of the objects become eligible for GC when the method returns. It depends what the caller does with the returned Collection. If they simply drop the returned Collection, then the Collection will be eligible for GC on return. If they store a reference to the returned Collection, then it will not be eligible, and neither will any of the objects it contains.

Normally, the objects in the Collection would become eligible for GC when the Collection does. But, if there are other references to them, they won't.

Basically, there's nothing special about Collections. All objects are eligible for GC when no-one has a reference to them.

(*) unless you are attempting a single allocation (e.g. big array) that's bigger than all the GCable objects put together.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the objects inside a collections are "guaranteed" to GC


You may think this is a useless distinction but I think it is important.

Do NOT think "I am storing an object in this collection."

Instead think "I am storing a reference to an object in this collection."

With this distinction in mind it should become clear that whether or not an object is eligible for GC depends on existance of a reference anywhere in your program.

Bill
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!