D. Alvarado said:
I have read on this newsgroup that despite the "gc" method, one cannot
actually force garbage collection. I am using Java 1.3. and I was
wondering Iif I can induce it more quicly by setting certain objects
to "null" in my code? Does anyone else have any suggestions for
"forcing" garbage collection?
It's often said that using System.gc() does not force garbage
collection. However, the truth is more complicated. Certainly
System.gc() is the best shot you have at inducing a garbage collection
to occur, and you can be almost sure that one will happen if you call
that method. The API documentation for System.gc() says that "When
control returns from the method call, the Java Virtual Machine has made
a best effort to reclaim space from all discarded objects."
It's important to realize that that's not the same as saying that a
garbage collection will occur. For example, if there are some
concurrency constraints on garbage collection, then it may not be
possible to do any work at this time; in that case, a "best effort" is
no effort at all. It's also possible that the garbage collector is not
deferred; in other words, objects are garbage collected immediately, so
there may not be any work to be done.
What's more often meant by saying that you can't force garbage
collection is that there is no guarantee that an unreferenced object
will be freed by a call to System.gc(). There is, in fact, never a
guarantee that any unreferenced object will be freed, ever. For one
thing, conservative collectors will tend to retain a very small
percentage of objects accidentally, and the specification is designed to
allow them.
===
As for "setting certain objects to null": You may have your terminology
confused, or you may be confused about concepts. You can never set an
object to null. The null value is a possible value for a reference, and
indicates that it does not point to an object. When you set a reference
to null, the object it points to is still there but just isn't pointed
to by that reference any longer.
You should never set a reference to null just to encourage garbage
collection to happen sooner; it doesn't work, and it clutters your code.
There are a few rare instances where you may need to set a reference to
null to permit garbage collection to collect an object graph in the
first place, though. These situations, and a few other tips, are
mentioned at the bottom of
http://jinx.swiki.net/59, which I wrote a
couple years ago to address this topic.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation